具有与分页相关的多个状态变化的Mysql查询

时间:2013-03-07 06:41:18

标签: mysql

我有这样的表

id  |  eventid   |  category  | type
----+------------+------------+------
1   |      1     |  music     | event
2   |      2     |  music     | event
3   |      3     |  music     | event
4   |      4     |  music     | event
5   |      5     |  music     | page
6   |      6     |  music     | page

现在我需要获取4条记录的数据,其中2条来自具有状态事件的表,2条来自具有状态页的表

示例:

id  |  eventid   |  category  | type
----+------------+------------+------
1   |      1     |  music     | event
2   |      2     |  music     | event

5   |      5     |  music     | page
6   |      6     |  music     | page

我已尝试使用以下查询但我收到错误

SELECT * 
FROM event_subcategory
WHERE category =  'music'
AND TYPE =  'event'
LIMIT 2 
UNION 
SELECT * 
FROM event_subcategory
WHERE TYPE =  'page'
LIMIT 2 

2 个答案:

答案 0 :(得分:0)

如果你想在LIMIT中使用UNION,最好在子查询周围使用括号,这样你就可以确保限制正确的选择,没有它们,第二个{{1适用于两个子选择。这更像我认为你想要它;

LIMIT

An SQLfiddle to test with

(作为旁注,你可能也希望将(SELECT * FROM event_subcategory WHERE category = 'music' AND TYPE = 'event' LIMIT 2) UNION (SELECT * FROM event_subcategory WHERE TYPE = 'page' LIMIT 2) 添加到你的第二个子查询,因为这两个部分是完全独立的)

答案 1 :(得分:0)

您可以尝试此查询

SET @level = 0;
SET @group = '';

SELECT 
        id,
        eventid,
        category,
        typ
FROM (
    SELECT 
        id,
        eventid,
        category,
        type,
        @level := IF(@group = type, @level+1, 1) AS level, 
        @group := type as EGroup 
    FROM event_subcategory
    ORDER BY `type`
) rs
WHERE level < 3 

这将从每个组中选择两个记录。您可以在where内部查询中放置where条件。使用union,你可以像这样打电话

(SELECT * FROM event_subcategory WHERE `TYPE` = 'event' LIMIT 2)
UNION ALL
(SELECT * FROM event_subcategory WHERE `TYPE` = 'page' LIMIT 2)