如何在SQL中选择两个表之间没有匹配的行?

问题描述 投票:1回答:3

我有两个表t1和t2

t1

plant  country    cost
------------------------
apple  usa        1
apple  uk         1
potato sudan      3
potato india      3
potato china      3
apple  usa        2
apple  uk         2


t2

country
--------
usa
uk
egypt
sudan
india
china

我需要为t1中不存在的国家/地区返回一个表格,如下所示:

plant  country    cost
------------------------
apple  egypt      1
apple  sudan      1
apple  india      1
apple  china      1
apple  egypt      2
apple  sudan      2
apple  india      2
apple  china      2
potato usa        3
potato uk         3
potato egypt      3

这似乎很容易但我无法解决它。我试过了:

select t1.plant, t2.country, t1.cost
from t1
right outer join t1 on t1.country = t2.country
where t2 is null
group by t1.plant, t2.country, t1.cost

我在堆栈溢出中查看了几个“不存在”的问题,但是响应不起作用,因为t1和t2之间的共同列比我的示例中更多。有人可以指出我正确的方向或向我显示类似问题的链接?

sql sql-server join
3个回答
2
投票

我们可以尝试通过使用即时日历表来处理这个问题:

WITH cte AS (
    SELECT DISTINCT t1.plant, t2.country, t1.cost
    FROM t1
    CROSS JOIN t2
)

SELECT
    a.plant,
    a.country,
    a.cost
FROM cte a
WHERE NOT EXISTS (SELECT 1 FROM t1 b
                  WHERE a.plant = b.plant AND
                        a.country = b.country AND
                        a.cost = b.cost);

Demo


0
投票

您可以使用CROSS JOIN生成plantscountires的所有可能组合,然后使用相关子查询的NOT EXISTS条件来过滤掉t2中存在的那些:

select plants.plant, countries.country, plants.cost
from t2 countries
cross join (distinct plant, max(cost) cost from t1 group by plant) plants
where not exists (
    select 1 from t1 where t1.country = countries.country
)

0
投票
SELECT t.plant, t2.country, t.cost
FROM(
SELECT DISTINCT plant , cost
FROM t1)t
CROSS JOIN t2
LEFT JOIN t1 ON t1.plant = t.plant and t1.country = t2.country AND t.cost = t1.cost
WHERE t1.plant IS NULL AND t1.country IS NULL AND t1.cost is NULL
© www.soinside.com 2019 - 2024. All rights reserved.