在我的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
不会检索任何结果
关于这个例子,我希望它返回serial_id为1和2的两行,所以结果如下:
series_id
1
4
(可选/奖金)如果可以提出另一种解决方案或利用:
GROUP_CONCAT(category_id SEPARATOR ', ') AS category
从此查询返回的series_id,因此返回的结果为:
series_id category
1 1, 2, 3
4 1, 2
非常感谢。感谢您抽出时间帮助我解决这一具有挑战性的问题。
答案 0 :(得分: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上查看。
答案 1 :(得分: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
希望这会对你有所帮助。