当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL中union和order by同时使用的实现方法

MySQL中union和order by同时使用的实现方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

mysql中union和order by是可以一起使用的,但是在使用中需要注意一些小问题,下面通过例子来说明。首先看下面的t1表。

1、如果直接用如下sql语句是会报错:incorrect usage of union and order by。

select * from t1 where username like 'l%' order by score asc
union
select * from t1 where username like '%m%' order by score asc

因为union在没有括号的情况下只能使用一个order by,所以报错,这个语句有2种修改方法。如下:

(1)可以将前面一个order by去掉,改成如下:

select * from t1 where username like 'l%'
union
select * from t1 where username like '%m%' order by score asc

该sql的意思就是先union,然后对整个结果集进行order by。

(2)可以通过两个查询分别加括号的方式,改成如下:

(select * from t1 where username like 'l%' order by sroce asc)
union
(select * from t1 where username like '%m%' order by score asc)

这种方式的目的是为了让两个结果集先分别order by,然后再对两个结果集进行union。但是你会发现这种方式虽然不报错了,但是两个order by并没有效果,所以应该改成如下:

select * from
(select * from t1 where username like 'l%' order by score asc) t3
union
select * from
(select * from t1 where username like '%m%' order by score asc) t4

也就是说,order by不能直接出现在union的子句中,但是可以出现在子句的子句中。

2、顺便提一句,union和union all 的区别。

union会过滤掉两个结果集中重复的行,而union all不会过滤掉重复行。

以上这篇mysql中union和order by同时使用的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网