解决sql中union后面不能使用order by和limit问题

有一种场景,我们需要在同一张表中找出几个分类的文章,并且按照时间排序,通常我们会这样写:

select * from 表 where type=1 order by create_time desc limit 10

如果有多个分类,我们会考虑将几个语句使用union 或者 union all 连接

select * from 表 where type=1 order by create_time desc limit 10
union all
select * from 表 where type=2 order by create_time desc limit 10

但是这样写是错误的,sql中的order by 和limit 是不能在union 句子中执行的。

解决方式是:

(select * from 表 where type=1 order by create_time desc limit 10)
union all
(select * from 表 where type=1 order by create_time desc limit 10)

或者

select * from(select * from 表 where type=1 order by create_time desc limit 10) a 
union all
select * from(select * from 表 where type=1 order by create_time desc limit 10) b

 

posted @   哩个啷个波  阅读(1149)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示