2

在我的 MySQL 数据库中,我有两个这样的列设置(例如):

series_id   category_id
    1            1
    1            2
    1            3
    2            1
    2            3
    3            2
    4            1
    4            2

当 category_id = 1 和 2 时,我可以用来选择 series_id 的正确选择查询是什么?

当前查询是这样的:

SELECT series_id 
FROM table 
WHERE category_id = '1' 
OR category_id = '2' 
GROUP BY series_id"

这不会检索任何结果:

SELECT series_id 
FROM table 
WHERE category_id = '1' 
AND category_id = '2' 
GROUP BY series_id

关于此示例,我希望它返回 series_id 为 1 和 2 的两行,因此结果如下所示:

series_id
     1
     4

(可选/奖励)如果可以提出其他解决方案或利用:

GROUP_CONCAT(category_id SEPARATOR ', ') AS category

对于此查询返回的 series_id (s),因此返回的结果是:

series_id    category
     1       1, 2, 3
     4       1, 2
4

2 回答 2

4
SELECT   series_id
FROM     my_table
WHERE    category_id IN (1,2)
GROUP BY series_id
HAVING   COUNT(*) = 2

sqlfiddle上查看。

请注意,如果(series_id, category_id)不能保证是唯一的,则应替换COUNT(*)为性能较差的COUNT(DISTINCT category_id).

要返回分组结果,您可以再次加入您的表:

SELECT series_id, GROUP_CONCAT(category_id)
FROM   my_table NATURAL JOIN (
  SELECT   series_id
  FROM     my_table
  WHERE    category_id IN (1,2)
  GROUP BY series_id
  HAVING   COUNT(*) = 2
) t
GROUP BY series_id

sqlfiddle上查看。

于 2012-09-07T12:33:59.837 回答
2

您需要SubQuery获取series_id`GROUP_CONCAT.

SELECT series_ID, GROUP_CONCAT(category_id)
FROM tableName
WHERE series_ID IN
        (
            SELECT series_id
            FROM tableName
            WHERE Category_ID IN (1,2)
            GROUP BY seriesID
            HAVING COUNT(series_id) = 2
        )
GROUP BY series_ID

SQLFiddle 演示

希望这对您有所帮助。

在此处输入图像描述

于 2012-09-07T12:36:03.710 回答