查找具有多个关系的实体

时间:2014-07-31 17:17:13

标签: mysql sql doctrine

鉴于模型

Photo
======
id

PhotoConnect
======
outside_name
outside_key
photo_id (foreign key to Photo)

我如何找到所有带有PhotoConnect的{​​{1}} = outside_namecountry = outside_key}和({{ {1}} = 6outside_name = region)?

到目前为止,我已经尝试了内部加入表格和outside_key两者,但没有成功。

1 个答案:

答案 0 :(得分:1)

听起来你想第二次加入这个表......国家或地区的匹配条件

SELECT 
    p.id 
FROM Photo p
JOIN PhotoConnect pc on pc.photo_id = p.id
JOIN PhotoConnect pc1 on pc1.photo_id = p.id
WHERE pc.outside_name = 'country' and pc.outside_key = 6 
  AND pc1.outside_name = 'region' and pc1.outside_key = 13
GROUP BY photo_id