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