sql - 如何在 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 之间的共同列比我的示例中的多。有人可以指出我正确的方向或向我显示类似问题的链接吗?
解决方案
我们可以尝试通过使用动态日历表来处理这个问题:
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);
演示
推荐阅读
- java - Gradle:从命令行将参数传递给编译器
- c - 使用彼此的数据类型(2 Header)
- rust - 如何将路径传递给 Command::arg?
- elasticsearch - 在 Elasticsearch 中提升元组
- android - 设置内容视频的大小
- c# - 检查字符串是否等于双精度
- reactjs - Locating database file
- c# - SQL 代码用于连接和汇总数据,由逗号分隔的键引用的表
- java - 无法执行目标 org.apache.maven.plugins:maven-site-plugin:3.7:site (default-cli):常量池中的无效字节标签:18
- unit-testing - Firebase 功能离线测试存根