SQL - 使用多个条件加入

时间:2015-09-23 10:13:22

标签: mysql sql

我有3张桌子:

食谱:id - name

条件:id - name

recipe_has_criterias :id - id_recipe - id_criteria

例如,在 recipe_has_criterias

1 - 1 - 1

2 - 1 - 2

3 - 2 - 1

我想获得标准1和2的配方(这里的食谱为id 1)

我该怎么做?

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

select r.name
from recipe r
join recipe_has_criterias rc on r.id = rc.id_recipe
where rc.id_criteria in (2,3)
group by r.name
having count(distinct rc.id_criteria) = 2

答案 1 :(得分:0)

select a.*,b.*,c.*
from recipe_has_criterias a
inner join recipe b
on b.id=a.id_recipe
inner join criteria c
on c.id=a. id_criteria and a. id_criteria in(2,3)

答案 2 :(得分:0)

执行2个连接,每个标准对应一个: -

SELECT r.name
FROM recipe r
INNER JOIN recipe_has_criteria rc1
ON r.id = rc1.id_recipe
INNER JOIN recipe_has_criteria rc2
ON r.id = rc2.id_recipe
WHERE rc1.id_criteria = 2
AND rc2.id_criteria = 3