[英]MySQL - Combine two queries, or limit results
I have a table that tracks recently updated pages, each page has a type. 我有一个表来跟踪最近更新的页面,每个页面都有一个类型。 I want to limit the results so that we only pull 3 pages of type x, and 3 of type y, but still have them sorted by lastUpdated.
我想限制结果,以便我们只提取3个类型为x的页面和3个类型为y的页面,但仍按lastUpdated对其进行排序。 I can't figure out how to do this in mysql
我不知道如何在mysql中执行此操作
SELECT * from recentlyUpdated WHERE type = 'x' DESC LIMIT 3
SELECT * from recentlyUpdated WHERE type = 'y' DESC LIMIT 3
then ... 然后 ...
ORDER BY lastUpdated DESC
This may help you;) 这可能对您有帮助;)
(SELECT * from recentlyUpdated WHERE type = 'x'lastUpdated ORDER BY DESC LIMIT 3)
UNION ALL
(SELECT * from recentlyUpdated WHERE type = 'y'lastUpdated ORDER BY DESC LIMIT 3)
ORDER BY lastUpdated DESC
One obvious way to do it is using UNION
: 一种明显的方法是使用
UNION
:
SELECT *
FROM (
SELECT *
FROM recentlyUpdated
WHERE type = 'x'
LIMIT 3
UNION ALL
SELECT *
FROM recentlyUpdated
WHERE type = 'y'
LIMIT 3) AS t
ORDER BY lastUpdated DESC
Alternatively, you can use variables: 另外,您可以使用变量:
SELECT *
FROM (
SELECT *,
@seq := IF(@t = type, @seq + 1,
IF(@t := type, 1, 1)) AS seq
FROM recentlyUpdated
CROSS JOIN (SELECT @seq := 0, @t := '') AS vars
WHERE type IN ('x', 'y')
ORDER BY type) AS t
WHERE t.seq <= 3
ORDER BY lastUpdated DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.