如何解决如何结合多个选择语句和每个限制
列cat
具有三个不同的值-lorem
,ipsum
和dolor
需要从每个类别(15 rows
)中选择cat
,即45 rows total
用union
尝试过-没有成功
有帮助吗?
select id,title from arts where cat = 'lorem' order by ind asc limit 15
union
select id,title from arts where cat = 'ipsum' order by ind asc limit 15
union
select id,title from arts where cat = 'dolor' order by ind asc limit 15
解决方法
必需的语法是将各个限制查询包装在括号内,如下所示
(select id,title from arts where cat = 'lorem' order by ind asc limit 15)
union
(select id,title from arts where cat = 'ipsum' order by ind asc limit 15)
union
(select id,title from arts where cat = 'dolor' order by ind asc limit 15)
,将ORDER BY或LIMIT子句应用于单个SELECT [ 联合],在SELECT上加上括号,然后将子句放在 括号...
如果您正在运行MySQL 8.0,则可以使用窗口函数来做到这一点:
select id,title
from (
select a.*,row_number() over(partition by cat order by ind) rn
from arts a
where cat in ('lorem','ipsum','dolor')
) t
order by cat,ind
您可以控制外层order by
返回行的顺序:这按类别对行进行排序,然后按ind
进行排序。
这应该比union all
更有效,因为该表仅扫描一次。
您要按ID订购吗?如果是这样...
你应该做
SELECT * FROM
(
(SELECT id,title from arts where cat = 'lorem' ORDER BY id LIMIT 15)
UNION ALL
(SELECT id,title from arts where cat = 'ipsum' ORDER BY id LIMIT 15)
UNION ALL
(SELECT id,title from arts where cat = 'dolor' ORDER BY id LIMIT 15)
) AS result;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。