首页 > 解决方案 > 如何在 SQL 中选择两个表之间不匹配的行?

问题描述

我有两张桌子 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 之间的共同列比我的示例中的多。有人可以指出我正确的方向或向我显示类似问题的链接吗?

标签: sqlsql-serverjoin

解决方案


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

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);

演示


推荐阅读