gpt4 book ai didi

mysql - 在 SQL 中的同一字段上同时使用运算(或)与(和)(而不是不同的字段)

转载 作者:行者123 更新时间:2023-11-29 09:30:49 25 4
gpt4 key购买 nike

我有三个表,多对多关系

enter image description here

如果我插入数据,表格将如下所示

enter image description here

我想获取产品名称,其中 (propertyValue='ios' 或 propertyValue = 'android') 和 (propertyValue='black')

换句话说,我们可以说

我想获取产品名称,其中 (propertyid='2' 或 propertyid = '4') 和 (propertyid='3')

我尝试了第二种方法,有一条SQL:

Select DISTINCT(p.productname),p.productid
from Products p
left join Product_propertyvalue ppv on p.productid=ppv.productid
where ( ppv.propertyvalueid=2 or ppv.propertyvalueid=4) and ( ppv.propertyvalueid=3 )

最佳答案

您可以使用having:

select p.productname, p.productid
from Products p left join
Product_propertyvalue ppv
on p.productid = ppv.productid
group by p.productname, p.productid
having sum( ppv.propertyvalueid in (2, 4) ) > 0 and
sum( ppv.propertyvalueid = 3 ) > 0;

sum() 条件检查给定产品的每个属性是否存在。

关于mysql - 在 SQL 中的同一字段上同时使用运算(或)与(和)(而不是不同的字段),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58790835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com