1.SELECT子句
字句名稱 使用目的
select 確定結果集中應該包含哪些列
from ? ?指明所要提取數據的表,以及這些表示如何連接的
where 過濾掉不需要的數據
group by 用于對具有相同列值的行進行分組
having 過濾掉不需要的組
order by ?按一個或多個列,對最后結構集中的行進行排序
現在假如我有一個員工表,主要有4個字段,id(員工id)、fname(姓)、lname(名字)、work_date(時間)。
--建表
CREATE?TABLE?`user`?(
`id`?int(11)?unsigned?NOT?NULL?AUTO_INCREMENT?COMMENT?'ID',
`category`?varchar(20)?COLLATE?utf8_turkish_ci?NOT?NULL?COMMENT?'類別',
`parentid`?int(11)?NOT?NULL?DEFAULT?'0'?COMMENT?'上級',
`work_date`?int(11)?NOT?NULL?COMMENT?'時間,
PRIMARY?KEY?(`id`),
KEY?`fl`?(`createtime`)
)?ENGINE=InnoDB?AUTO_INCREMENT=46056?DEFAULT?CHARSET=utf8?COLLATE=utf8_turkish_ci;
--添加內容
--查詢
(1)如何獲得員工id為99號的員工的所有信息?
(2)如何獲得id?大于等于20,小于等于40的員工信息?(請用兩種不同方式分別實現)
(3)如何獲得11,45,99,124號員工的信息?(用兩種方式實現)
(4)如何獲得除了11,45,99,124號員工外,其他員工的信息?(用兩種方式實現)
(5)如何獲得入職時間在2011年10月1日前的,并且姓 ‘李’的所有員工?(用三種方式實現)
(6)如何獲取所有emp_id的末尾為1的所有記錄,比如emp_id為1,11,21,31.。。。101,121,。。。1001,1011,。。。。。(用三種方式來實現)
(7)如何獲取101,111,121,131,141,151,161,171,181,191這幾個員工的記錄?(分別用通配和正則來實現)
上面的這些問題基本涵蓋了where語句中的所有知識點,大家可以先試試看,按照題目的描述和括號中的條件來實現。
思考后,再查看下面的答案。
答案:
(1)select * from employee where emp_id = 99;
(2)select * from employee where emp_id between 20 and 40;
select * from employee where emp_id >=20 and emp_id <=40;
(3)select * from employee where emp_id = 11 or emp_id = 45 or emp_id = 99 or emp_id = 124;
select * from employee where emp_id in (11,45,99,124);
(4)select * from employee where emp_id !=11 and emp_id !=45 and emp_id != 99 and emp_id !=124;
select * from employee where emp_id not in (11,45,99,124);
(5)select * from employee where start_date
select * from (select * from employee where fname = '李' )? d? where d.start_date < '2011-10-01';
select * from employee where emp_id in (select emp_id from employee where fname = '李' ) and start_date < '2011-10-01';
(6)select * from employee where emp_id like '%1';
select * from employee where emp_id regexp '.*1$';
select * from employee where right(emp_id,1) = 1;
(7)select * from employee where emp_id like '1_1;'
select * from employee where emp_id regexp '1.1';