没有相交sql查询获取相互id

时间:2018-01-31 11:48:22

标签: mysql sql intersection

我需要一个select查询来根据输入

获取L_IDs的相互R_ID
L_ID | R_ID|  
-----|-----|   
 1   |  1  |
 2   |  1  |
 3   |  1  |
 1   |  2  |
 2   |  2  |
 4   |  2  |
 2   |  3  |
 3   |  3  |
 4   |  3  |
 5   |  3  |
 ..

例如,如果我传递1,2,3:它返回1

SELECT R_ID FROM table WHERE L_ID in (1,2,3)

R_ID |   
-----|  
 1   |

例如,如果我通过2,3,4,5:它返回3

SELECT R_ID FROM table WHERE L_ID in (4,2,3,5)

R_ID |   
-----|  
 3   |

注意: L_ID的所有组合(1,2,3)都是唯一的,具有共同的R_ID

1 个答案:

答案 0 :(得分:1)

您可以使用group byhaving。我认为这样做你想要的:

SELECT R_ID
FROM table
WHERE L_ID in (1, 2, 3)
GROUP BY R_ID
HAVING COUNT(*) = 3;  -- this value is the number of matches

请注意,包含1,2,3和4的R_ID将匹配。如果这是不可取的,那么:

SELECT R_ID
FROM table
GROUP BY R_ID
HAVING SUM(L_ID IN (1, 2, 3)) = 3 AND
       COUNT(*) = 3;