Mysql查询时使用UNION和ORDER BY的问题

问题:
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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值