连接两个表,跨越所有记录。

huangapple go评论74阅读模式
英文:

JOIN of 2 tables where cross all records

问题

根据这两个表格,你可以编写以下查询来获取与MyConditions表中的所有记录匹配的MyValues表中的Ids,其中MyValues.IdValue = MyConditions.IdValue:

SELECT mv.Id
FROM MyValues mv
WHERE mv.IdValue IN (SELECT DISTINCT mc.IdValue FROM MyConditions mc)
GROUP BY mv.Id
HAVING COUNT(DISTINCT mv.IdValue) = (SELECT COUNT(DISTINCT mc.IdValue) FROM MyConditions mc);

查询的结果将是1,因为MyValues表中的Id 1与MyConditions表中的所有记录匹配。

英文:

Given these 2 tables

Table name: MyValues

Id IdValue
1 10
2 10
3 10
1 11

Table name: MyConditions

Id IdValue
7 10
7 11

How could I write a query to get the Ids from the MyValues table to return the ones that match all the records on MyConditions table where MyValues.IdValue = MyConditions.IdValue

So the result would be 1 (since Id 1 from MyValues table matches all records in MyConditions table)

答案1

得分: 2

这似乎是一个关系除法问题。我们可以使用joinhaving来连接和筛选:

select v.id
from myvalues v
inner join myconditions c on c.idvalue = v.idvalue
group by v.id
having count(*) = (select count(*) from myconditions)

这假设在myvalue中没有重复的(id, idvalue),并且在mycondition中没有重复的idvalue。否则,我们通常会在having的一侧或两侧使用distinct

having count(distinct v.idvalue) = (select count(distinct idvalue) from myconditions)
英文:

This reads like a relational division problem. We can join, and filter with having:

select v.id
from myvalues v
inner join myconditions c on c.idvalue = v.idvalue
group by v.id
having count(*) = (select count(*) from myconditions)

This assumes no duplicate (id, idvalue) in myvalue, and no duplicate idvalue in mycondition. Otherwise, we would typically use distinct on one or both side of having:

having count(distinct v.idvalue) = (select count(distinct idvalue) from myconditions)

huangapple
  • 本文由 发表于 2023年6月6日 16:54:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定