mylzdy的gravatar头像
mylzdy 2015-08-27 10:25:15

mysql数据库多个表union all查询并排序的结果为什么错误?

群主,我想进行一个表的查询,先把表中某个字段的内容查出,然后其他的再排序,我用union all连接两个表的查询结果排序是错的

比如我的sql语句:

select * from student t where t.name='aa' order by t.date desc

union all

select from student_1 s where s.name='bb' order by s.date desc

这两个查询出来的结果拼接到一起,按照原定的根据时间排序被打乱,现在想先将aa的查询出来,后面属于bb的按照时间进行排序。

所有回答列表(10)
longhupeng0的gravatar头像
longhupeng0  LV4 2015年8月27日

你想法是好的,

不过SQLServer不支持这样操作,

原因是order by 的优先级比 union all要低,所以一旦同时出新order 和 union 

会先执行union , 再执行order 

评论(2) 最佳答案
最代码官方的gravatar头像
最代码官方  LV167 2015年8月27日

我之前也有遇到类似的业务。

mysql sql查询如何实现发私信用户和其他用户的列表?要求消重所有重复的用户结果

思路就是把多个数据集union all到一个集合然后对这个集合的某个字段order by就没问题。

遇见,的gravatar头像
遇见,  LV36 2015年8月27日
select * from (select * from student t where t.name='aa'
union all
select * from student_1 s where s.name='bb') T order by T.date desc

 

hrose12的gravatar头像
hrose12  LV21 2015年8月28日

select * from student t where t.name='aa'

union all

select from student_1 s where s.name='bb' order by date desc

571039838的gravatar头像
571039838  LV2 2015年8月28日

gf打工的发生个电饭锅电饭锅电饭锅电饭锅的非官方大哥的非官方的所发生的

一个人的咖啡的gravatar头像
一个人的咖啡  LV5 2015年8月28日

可以把union all的结果整合起来进行order by

dragonsoft的gravatar头像
dragonsoft  LV2 2015年8月28日

可以把union all的结果整合起来进行order by

AloneX的gravatar头像
AloneX  LV6 2015年8月29日

可以把union all的结果整合起来进行order by

diaodiaofly的gravatar头像
diaodiaofly  LV21 2015年8月30日

select * from (

select * from student t where t.name='aa'

union all

select from student_1 s where s.name='bb'

) tmp order by tmp.date desc

 

面对疾风吧的gravatar头像
面对疾风吧  LV2 2015年9月6日

select * from (

select * from student t where t.name='aa'

union all

select from student_1 s where s.name='bb'

) tmp order by tmp.date desc

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友