获取分组后统计数量最多的纪录;limit用法;sql执行顺序
CREATE TABLE emp(
id INT PRIMARY KEY,
NAME VARCHAR(11),
dep_id INT ,
salary INT
);
CREATE TABLE dept(
id INT PRIMARY KEY,
NAME VARCHAR(11),
parentid INT);
获取各部门人数信息:
SELECT e.dep_id,d.name,COUNT(e.dep_id) FROM emp e,dept d WHERE e.dep_id=d.id GROUP BY e.dep_id;
统计部门人数最多的部门:
SELECT e.dep_id,d.name,COUNT(e.dep_id) numbers FROM emp e,dept d WHERE e.dep_id=d.id GROUP BY e.dep_id ORDER BY numbers DESC LIMIT 1;
limit用法:
LIMIT 5,10; // 检索记录行 6-15
LIMIT 95,-1; // 检索记录行 96-last.
LIMIT 5; //检索前 5 个记录行
sql执行顺序:
写的顺序:select ... from... where.... group by... having... order by.. limit [offset,]
(rows)
执行顺序:from... where...group by... having.... select ... order by... limit
(1)from
(3) join
(2) on
(4) where
(5)group by(开始使用select中的别名,后面的语句中都可以使用)
(6) avg,sum....
(7)having
(8) select
(9) distinct
(10) order by