1

我有这样的桌子

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 
4

2 回答 2

0

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

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

一个用于测试的 SQLfiddle

(作为旁注,您可能还想添加WHERE category = 'music'到您的第二个子查询,因为这两个部分是完全独立的)

于 2013-03-07T06:47:47.540 回答
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 条件。使用联合,您可以这样调用

(SELECT * FROM event_subcategory WHERE `TYPE` = 'event' LIMIT 2)
UNION ALL
(SELECT * FROM event_subcategory WHERE `TYPE` = 'page' LIMIT 2)
于 2013-03-07T06:48:34.693 回答