[英]Multi-row SELECT query on SINGLE column
In my MySQL database I have two columns setup like this (for example):在我的 MySQL 数据库中,我有两列设置如下(例如):
series_id category_id
1 1
1 2
1 3
2 1
2 3
3 2
4 1
4 2
What is the proper select query I can use to select the series_id when the category_id = 1 and 2?当 category_id = 1 和 2 时,我可以用来选择 series_id 的正确选择查询是什么?
Current query is this:当前查询是这样的:
SELECT series_id
FROM table
WHERE category_id = '1'
OR category_id = '2'
GROUP BY series_id"
This does not retrieve any results:这不会检索任何结果:
SELECT series_id
FROM table
WHERE category_id = '1'
AND category_id = '2'
GROUP BY series_id
In regards to this example I would like it to return the two rows where the series_id is 1 and 2 so the result looks like this:关于此示例,我希望它返回 series_id 为 1 和 2 的两行,因此结果如下所示:
series_id
1
4
(Optional / Bonus) If it is possible to come up with another solution or utilize: (可选/奖励)如果可以提出另一种解决方案或利用:
GROUP_CONCAT(category_id SEPARATOR ', ') AS category
for the returned series_id (s) from this query so the returned result is:对于从此查询返回的 series_id (s),返回的结果是:
series_id category
1 1, 2, 3
4 1, 2
SELECT series_id
FROM my_table
WHERE category_id IN (1,2)
GROUP BY series_id
HAVING COUNT(*) = 2
See it on sqlfiddle .在sqlfiddle上查看。
Note that if (series_id, category_id)
are not guaranteed to be unique, you should replace COUNT(*)
with the less performant COUNT(DISTINCT category_id)
.请注意,如果
(series_id, category_id)
不能保证是唯一的,则应将COUNT(*)
替换为性能较低的COUNT(DISTINCT category_id)
。
To return the grouped results, you can join against your table again:要返回分组结果,您可以再次加入您的表:
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
You need to have SubQuery
to get the series_id
so that later on you can use `GROUP_CONCAT.您需要使用
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
Hope this helps you.希望这对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.