[英]How to select all records in a table excluding records from another
I have 2 tables that hold information about pages and any categories that the pages belong to, the pages do not have to have any category and can also be in multiple categories. 我有2个表,这些表包含有关页面以及页面所属的任何类别的信息,页面不必具有任何类别,也可以处于多个类别中。
page
pageid title
1 page1
2 page2
3 page3
4 page4
category
pageid category
2 cat1
2 obsolete
3 cat2
I want to write a query that will select all pages as long as they are not categorised as 'obsolete'. 我想写一个查询,将选择所有页面,只要它们没有被归类为“过时”即可。
From the above, the output I am looking for is : 从上面,我正在寻找的输出是:
1 page1
3 page3
4 page4
So page 2 is excluded as one of its categories is 'obsolete' all other rows in the page table should be listed only once even if they have no categories or multiple categories in the category table. 因此,将第2页排除在外,因为它的类别之一“已过时”,即使表类别中没有任何类别或多个类别,页面表格中的所有其他行也应仅列出一次。
I have tried multiple combinations of subquery and joins but cannot achieve the output I am looking to produce. 我尝试了子查询和联接的多种组合,但是无法实现我想要产生的输出。
Use NOT EXISTS
使用NOT EXISTS
SELECT *
FROM page p
WHERE NOT EXISTS (SELECT pageid
FROM category c
WHERE p.pageid = c.pageid
AND category = 'obsolete');
Another way using Conditional Aggregate
and EXISTS
使用Conditional Aggregate
和EXISTS
另一种方法
SELECT *
FROM page p
WHERE EXISTS (SELECT 1
FROM category c
WHERE p.pageid = c.pageid
HAVING Count(CASE WHEN category = 'obsolete' THEN 1 END) = 0);
select * from page
where pageid not in (select pageid from category where category='obsolete');
or 要么
select distinct title from page
where pageid not in (select pageid from category where category='obsolete');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.