如何从2个表中计算“多边”实体一对多

时间:2014-02-02 15:37:51

标签: mysql sql

我有两个与MySQL中“一对多”关系相关的表。 如何从表1中选择ID('one-side'),在表2('many-side')中具有完全 N 相关值。 我试着用:

 SELECT target_id, COUNT(`target_id`) AS counter FROM `many_side_table` WHERE counter = N GROUP BY target_id; 

 SELECT target_id, COUNT(`target_id`) FROM `many_side_table` WHERE COUNT(`target_id`) = N GROUP BY target_id; 

但这是错误的......

2 个答案:

答案 0 :(得分:1)

我想你只想要having条款:

SELECT target_id, COUNT(`target_id`)
FROM `many_side_table`
GROUP BY target_id
HAVING COUNT(`target_id`) = N;

答案 1 :(得分:0)

SELECT target_id 
FROM many_side_table
GROUP BY target_id
HAVING COUNT(*) = N