我有一個表
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 BY
select * from test1 where name like 'A%' order by name
union
select * from test1 where name like 'B%' order by name
應改為:
select * from test1 where name like 'A%'
union
select * from test1 where name like 'B%' order by name
因為union中,在不用括弧的情況下,只能用一個order by(想一想,如果union兩邊的order by的列名不一樣會怎麼樣),這會對union後的結果集進行排序
或者改為:
(select * from test1 where name like 'A%' order by name)
union
(select * from test1 where name like 'B%' order by name)
這兩個order by在union前進行
(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不會過濾掉重複的行