问题:
Mysql中表student_table(id,name,birth,sex),查询男生、女生人数分别最多的3个姓氏及人数,正确的SQL是
A.
SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
from student_table where length(name) >=1 and sex = '男'
group by first_name order by sex ,c1 desc limit 3
union all
SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
from student_table where length(name) >=1 and sex = '女'
group by first_name order by sex ,c1 desc limit 3 ;
B.
select * from (
SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
from student_table where length(name) >=1 and sex = '男'
group by first_name order by sex ,c1 desc limit 3
) t1
UNION all
select * from (
SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
from student_table where length(name) >=1 and sex = '女'
group by first_name order by sex ,c1 desc limit 3
) t2 ;
问题分析:
A和B选项从表面来看是一样的,A是B的简写。但是在UNION(ALL)中使用ORDER BY子查询时要注意UNION连接的语句只会出现一个ORDER BY(不包含子查询中的),否则会报sql未正确结束的错误。
解决措施:
将含ORDER BY的子查询包在一个不含ORDER BY的查询里再进行UNION ALL。