SQL:使用SET运算符得到一个计数结果

SQL: Use SET operator to get a count result

我正在尝试在 SQL Developer 中使用 SET 运算符获取计数结果。

我必须找出有多少 "attribute1" 在 "table_name1" 中但不在 "table_name2"

本质上,我想要从以下查询中获得的结果,但使用的是 SET 运算符。

SELECT count(distinct <attribute1>)
FROM <table_name1>
WHERE <attribute1> IS NOT (SELECT <attribute1>
                           FROM <table_name2>);

谁能帮帮我?

请尝试以下解决方案:

SELECT count(distinct <attribute1>)
FROM <table_name1>
WHERE <attribute1> NOT IN (SELECT <attribute1>
                           FROM <table_name2>);

希望对您有所帮助。

如果您必须使用集合运算符,那么您可以使用 MINUS:

来解决这个问题
SELECT COUNT(*)                      -- use COUNT(DISTINCT attribute1) to avoid
FROM                                 -- duplicates
(
    SELECT attribute1
    FROM table_name1
    MINUS
    SELECT attribute1
    FROM table_name2
) t

不过,我可能会在这里使用 LEFT JOIN,因为它在概念上很简单:

SELECT COUNT(DISTINCT t1.attribute1) -- replace with COUNT(*) to count duplicates
FROM table_name1 t1
LEFT JOIN table_name2 t2
    ON t1.attribute1 = t2.attribute1
WHERE t2.attribute1 IS NULL          -- indicates that attribute does NOT appear in
                                     -- the second table
SELECT COUNT(<attribute1>)
FROM <table_name1>
WHERE <attribute1> MINUS (SELECT <attribute1>
                           FROM <table_name2>);

https://docs.oracle.com/cd/B19306_01/server.102/b14200/operators005.htm

更新答案

SELECT COUNT(X.id_num)
(SELECT id_num
FROM Tree 
WHERE id_num)
MINUS 
(SELECT id_num 
FROM Bird) AS X