mysql中的union和order by、limit

我有一個表spa

CREATE TABLE `test1` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `desc` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8排序

 

(1)如下查詢會報錯誤:[Err] 1221 - Incorrect usage of UNION and ORDER BYit

select * from test1 where name like 'A%' order by name
union
select * from test1 where name like 'B%' order by name
io

應改成:test

select * from test1 where name like 'A%'
union
select * from test1 where name like 'B%' order by name
select

由於union中,在不用括號的狀況下,只能用一個order by(想想,若是union兩邊的order by的列名不同會怎麼樣),這會對union後的結果集進行排序nio

或者改成:im

(select * from test1 where name like 'A%' order by name)
union
(select * from test1 where name like 'B%' order by name)
查詢

這兩個order by在union前進行co

 

(2)一樣的

select * from test1 where name like 'A%' limit 10
union
select * from test1 where name like 'B%' limit 20

至關於

(select * from test1 where name like 'A%' limit 10)
union
(select * from test1 where name like 'B%') limit 20

即後一個limit做用於的是union後的結果集,而不是union後的select

也能夠加括號來獲得你想要的結果

(select * from test1 where name like 'A%' limit 10)
union
(select * from test1 where name like 'B%' limit 20)

 

(3)UNION和UNION ALL區別

union會過濾掉union兩邊的select獲得的結果集中的重複的行,而union all不會過濾掉重複的行

相關文章
相關標籤/搜索