博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mysql中的union和order by、limit
阅读量:7009 次
发布时间:2019-06-28

本文共 1103 字,大约阅读时间需要 3 分钟。

 

我有一个表

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)

转载地址:http://nittl.baihongyu.com/

你可能感兴趣的文章
VBPR: Visual Bayesian Personalized Ranking from Implicit Feedback-AAAI2016 -20160422
查看>>
servlet injection analysis
查看>>
RNN 与 LSTM 的应用
查看>>
Linux服务器性能查看分析调优
查看>>
微信支付技术解决方案
查看>>
Vim 使用入门
查看>>
(原)centos7安装和使用greenplum4.3.12(详细版)
查看>>
深入学习Heritrix---解析CrawlController(转)
查看>>
HDU 6055 Regular polygon
查看>>
Hive之 hive与hadoop的联系
查看>>
linux和mac
查看>>
go 中的面向对象实现
查看>>
js 自定义弹窗方法
查看>>
Eclipse快捷键大全(转载)
查看>>
Install CentOS 7 on Thinkpad t430
查看>>
JavaScript中Date的一些细节
查看>>
趣味程序之趣味系列
查看>>
UVALive2389 ZOJ1078 Palindrom Numbers【回文+进制】
查看>>
ionic3使用echarts
查看>>
imuxsock lost 353 messages from pid 20261 due to rate-limiting 解决办法
查看>>