MySQL - 组合两个查询,或限制结果

时间:2016-06-17 08:24:44

标签: php mysql database

我有一个跟踪最近更新页面的表,每个页面都有一个类型。我想限制结果,以便我们只拉3页x型和3型y,但仍然按lastUpdated排序。我无法弄清楚如何在mysql中执行此操作

SELECT * from recentlyUpdated WHERE type = 'x' DESC LIMIT 3
SELECT * from recentlyUpdated WHERE type = 'y' DESC LIMIT 3

然后......

ORDER BY lastUpdated DESC

2 个答案:

答案 0 :(得分:4)

这可能会对你有帮助;)

(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

答案 1 :(得分:2)

一种显而易见的方法是使用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

或者,您可以使用变量:

  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