[英]How can I write a SQL query to find records related to a record in another table ignoring another record
I have a requirement to write a query that finds records related to a record in another table that aren't related to another record.我需要编写一个查询来查找与另一个表中与另一个记录无关的记录相关的记录。
Below is an example of what I mean.下面是我的意思的一个例子。 I will happily rewrite this question and title if I can express the question in a better way (advice welcome).如果我能以更好的方式表达这个问题,我会很乐意重写这个问题和标题(欢迎提出建议)。
Table company
表company
id
1
2
3
Table company_partner
表company_partner
id company_id company_name
1 1 Nike
2 1 Reebok
3 2 Nike
4 3 Nike
In the above example, I would like all companies partnered with Nike but not if they are also partnered with Rebook.在上面的示例中,我希望所有公司都与 Nike 合作,但如果他们也与 Rebook 合作,则不希望。 Using the above example that would be companies 2
and 3
.使用上面的例子,公司2
和3
。
I can write a query that gives me all companies partnered with Nike:我可以编写一个查询,为我提供所有与 Nike 合作的公司:
SELECT c.id
FROM company c
INNER JOIN company_partner cp ON c.id = cp.company_id
WHERE
cp.company_name = 'Nike'
-- ignore cp.company_name = 'Reebok' ???
I am unclear how I can ignore companies that are also partnered with Reebok?我不清楚我怎么能忽略也与 Reebok 合作的公司?
You should be able to use not in - like this:你应该可以使用 not in - 像这样:
SELECT c.id
FROM company c
INNER JOIN company_partner cp ON c.id = cp.company_id
WHERE cp.company_name = 'Nike'
AND c.id not in (
select id from company_partner where company_name = 'Reebok'
)
Aggregation provides one straightforward option:聚合提供了一种简单的选择:
SELECT company_id
FROM company_partner
GROUP BY company_id
HAVING COUNT(CASE WHEN company_name = 'Nike' THEN 1 END) > 0 AND
COUNT(CASE WHEN company_name = 'Reebok' THEN 1 END) = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.