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';