欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-17 09:00:16
mysql中union和order by是可以一起使用的,但是在使用中需要注意一些小问题,下面通过例子来说明。首先看下面的t1表。 1、如果直接用如下sql语句是会报...

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

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

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同时使用的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: