[英]How to select rows with no match between two tables in 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);
你可以使用一個CROSS JOIN
產生的所有可能組合plants
和countires
,那么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
)
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.