[英]How to return rows only where all supplied values are found in a mysql join?
I have an inner join like this:我有一个这样的内部连接:
SELECT
p.id
, p.date
, pu.user_id
FROM projections p
INNER JOIN projection_user AS pu ON p.id = pu.projection_id
WHERE pu.user_id IN ('1', '3')
This returns the following results:这将返回以下结果:
id | date | user_id
--------------------------
16 | 2020-03-05 | 1
17 | 2020-03-05 | 1
17 | 2020-03-05 | 3
I would like to only return rows where the projection ( p.id
) has the exact pu.user_id
values supplied in my WHERE
clause -- in this case the projection with a p.id
of 17, since it has both pu.user_id
1 and 3, and no others.我只想返回投影 ( p.id
) 具有在我的WHERE
子句中提供的确切pu.user_id
值的行——在这种情况下, p.id
为 17 的投影,因为它同时具有pu.user_id
1和 3,没有其他。 In the full code I am actually grouping by p.id
for the final result:在完整代码中,我实际上是按p.id
分组以获得最终结果:
SELECT
p.id
, p.date
FROM projections p
INNER JOIN projection_user AS pu ON p.id = pu.projection_id
WHERE pu.user_id IN ('1', '3')
GROUP BY p.id
id | date
--------------------------
16 | 2020-03-05
17 | 2020-03-05
How can I only return the projection with p.id
of 17?我怎样才能只返回p.id
为 17 的投影?
Use aggregation:使用聚合:
SELECT p.id, p.date, GROUP_CONCAT(pu.user_id)
FROM projections p INNER JOIN
projection_user pu
ON p.id = pu.projection_id
GROUP BY p.id, p.date
HAVING SUM(pu.user_id IN (1, 3)) = COUNT(*) AND
COUNT(*) = 2;
Note: This assumes no duplicates in projection_user
, which is typically a reasonable assumption.注:这是假设在没有重复projection_user
,这通常是一个合理的假设。 The query can be tweaked if such duplicates are possible.如果此类重复是可能的,则可以调整查询。
Or, if you prefer:或者,如果您更喜欢:
SELECT p.id, p.date,
GROUP_CONCAT(pu.user_id ORDER BY pu.user_id) as user_ids
FROM projections p INNER JOIN
projection_user pu
ON p.id = pu.projection_id
GROUP BY p.id, p.date
HAVING user_ids = '1,3';
This amendment to Gordon Linoff's answer works as needed:对 Gordon Linoff 的回答的这个修正根据需要起作用:
SELECT
p.id
, p.date
FROM projections p
INNER JOIN projection_user AS pu ON p.id = pu.projection_id
GROUP BY p.id
HAVING SUM(pu.user_id IN (1, 3)) = COUNT(*) AND COUNT(*) = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.