我有三张桌子:
表产品
ID | NAME
1 | cheese
2 | salami
3 | potato
4 | onion
5 | ananas
表格组件
ID | product_id | component_id
1 | 1 | 1
2 | 1 | 5
3 | 2 | 1
4 | 3 | 5
5 | 3 | 3
表product_components
<div fxLayout="row" fxLayout-gt-xs="column">
<mat-card fxflex fxflex-gt-xs="100" fxFlex="33.33%">
<h2>Card title #1</h2>
<mat-card-content>
<p>Some content</p>
</mat-card-content>
</mat-card>
<mat-card fxflex fxflex-gt-xs="100" fxFlex="33.33%">
<h2>Card title #2</h2>
<mat-card-content>
<p>Some content</p>
</mat-card-content>
</mat-card>
我想只买披萨奶酪和凤梨(披萨A)。我该怎么做?
答案 0 :(得分:0)
您需要使用Group By
和Having
子句
select p.Name
from product_components pc
inner join product p on pc.ID_PIZZA = p.id
where name in ('cheese' ,'salami')
Group by p.Name
having count(distinct pc.Name)= 2
上述查询将返回同时包含'cheese'
和'salami'
的Pizza。但同样的披萨也可以有其他一些成分。
或者如果您想要只有'cheese'
和'salami'
的披萨,那么您需要稍微调整Having
子句
select p.Name
from product_components pc
inner join product p on pc.ID_PIZZA = p.id
Group by p.Name
having sum(case when name in ('cheese' ,'salami') then 1 else 0 end) = count(*)
答案 1 :(得分:0)
SELECT P.Name FROM product P
INNER JOIN (SELECT ID_PIZZA, GROUP_CONCAT(name ORDER BY name) AS INGR
FROM product_components
GROUP BY ID_PIZZA
) t
ON T.ID_PIZZA = P.ID
AND T.INGR = 'cheese,salami'
答案 2 :(得分:0)
select p.name
from product p
join product_components c1 on c1.id_pizza = p.id
join product_components c2 on c2.id_pizza = p.id
where c1.name = 'cheese'
and c2.name = 'salami'
如果您想要排除不仅仅包含奶酪和萨拉米香肠的比萨饼,您可以使用“不包括LEFT JOIN”扩展查询:
select p.name
from product p
join product_components c1 on c1.id_pizza = p.id
join product_components c2 on c2.id_pizza = p.id
left join product_components other
on other.id_pizza = p.id
and other.name not in (c1.name, c2.name)
where c1.name = 'cheese'
and c2.name = 'salami'
and other.name is null
对于更改的架构,查询类似于
select p.name
from products p
join product_components pc1 on pc1.product_id = p.id
join components c1 on c1.id = pc1.component_id
join product_components pc2 on pc2.product_id = p.id
join components c2 on c2.id = pc2.component_id
where c1.name = 'cheese'
and c2.name = 'salami'
select p.name
from products p
join product_components pc1 on pc1.product_id = p.id
join components c1 on c1.id = pc1.component_id
join product_components pc2 on pc2.product_id = p.id
join components c2 on c2.id = pc2.component_id
left join product_components pco
on pco.product_id = p.id
and pco.component_id not in (pc1.component_id, pc2.component_id)
where c1.name = 'cheese'
and c2.name = 'salami'
and pco.component_id is null