我一直在努力寻找一种相对简单的方法来执行此查询。我尝试过 join 和 wheres,甚至尝试在查询之外执行逻辑,但它变得非常复杂。
这是我的 SQL:
AttributeName_Id | ProductPrice_Id
9 | 1
4 | 1
9 | 2
5 | 2
9 | 3
6 | 3
9 | 4
7 | 4
我有输入 9 和 5。我将如何执行查询以便检索值 2?
最佳答案
这是一个“组内组”查询。我喜欢使用group by
和having
来解决这些问题,因为它非常灵活:
select ProductPrice_Id
from table t
where AttributeName_Id in (9, 5)
group by ProductPrice_Id
having count(*) = 2;
这假设该表没有重复项;否则,您可能需要count(distinct)
。
关于mysql - SQL查询根据另一列中的唯一元素查找列中的公共(public)ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31819191/