1. 程式人生 > >表的增刪改查—例項

表的增刪改查—例項

例1:

對於表actor批量插入如下資料 CREATE TABLE IF NOT EXISTS actor ( actor_id smallint(5) NOT NULL PRIMARY KEY, first_name varchar(45) NOT NULL, last_name varchar(45) NOT NULL, last_update timestamp NOT NULL DEFAULT (datetime('now','localtime')))

actor_id first_name last_name last_update
1 PENELOPE GUINESS 2006-02-15 12:34:33
2 NICK WAHLBERG

2006-02-15 12:34:33

insert into actor values(1,'PENELOPE','GUINESS','2006-02-15 12:34:33'),(2,'NICK','WAHLBERG','2006-02-15 12:34:33');

 例2:

找出所有員工當前(to_date='9999-01-01')具體的薪水salary情況,對於相同的薪水只顯示一次,並按照逆序顯示 CREATE TABLE `salaries` ( `emp_no` int(11) NOT NULL, `salary` int(11) NOT NULL, `from_date` date NOT NULL, `to_date` date NOT NULL, PRIMARY KEY (`emp_no`,`from_date`));

輸入描述:

輸出描述:

salary
94692
94409
88958
88070
74057
72527
59755
43311
25828
select distinct salary from salaries where to_date='9999-01-01' order by salary desc;

 例3:

查詢最晚入職員工的所有資訊

CREATE TABLE `employees` ( `emp_no` int(11) NOT NULL, `birth_date` date NOT NULL, `first_name` varchar(14) NOT NULL, `last_name` varchar(16) NOT NULL, `gender` char(1) NOT NULL, `hire_date` date NOT NULL, PRIMARY KEY (`emp_no`));

輸入描述:

輸出描述:

emp_no birth_date first_name last_name gender hire_date
10008 1958-02-19 Saniya Kalloufi M 1994-09-15
select * from employees order by hire_date desc limit 0,1 ;

思路:先將全部資料進行降序排序,然後利用limit指令選取第一條資料。

 例4:

查詢入職員工時間排名倒數第三的員工所有資訊 CREATE TABLE `employees` ( `emp_no` int(11) NOT NULL, `birth_date` date NOT NULL, `first_name` varchar(14) NOT NULL, `last_name` varchar(16) NOT NULL, `gender` char(1) NOT NULL, `hire_date` date NOT NULL, PRIMARY KEY (`emp_no`));

輸入描述:

輸出描述:

emp_no birth_date first_name last_name gender hire_date
10005 1955-01-21 Kyoichi Maliniak M 1989-09-12
select * from employees order by hire_date desc limit 2,1 ;

思路:與上一道題相比較,只需要修改limit指令起始位置與記錄條數 。

例5:

查詢薪水漲幅超過15次的員工號emp_no以及其對應的漲幅次數t CREATE TABLE `salaries` ( `emp_no` int(11) NOT NULL, `salary` int(11) NOT NULL, `from_date` date NOT NULL, `to_date` date NOT NULL, PRIMARY KEY (`emp_no`,`from_date`));

輸入描述:

輸出描述:

emp_no t
10001 17
10004 16
10009 18
select emp_no,count(emp_no) as t from salaries group by emp_no having t>15;