sqlite 根据Sqite3中的一个表查找另一个表中缺少的行

nfzehxib  于 2022-11-30  发布在  SQLite
关注(0)|答案(1)|浏览(163)

我有两个表tournamentspinsheets。表如下所示:

CREATE TABLE "pinsheets" (
    "tournament"    INTEGER,
    "year"  INTEGER,
    "course"    INTEGER,
    "round" INTEGER,
    "hole"  INTEGER,
    "front" INTEGER,
    "side"  INTEGER,
    "region"    INTEGER
);

数据示例:

2   2015    6   1   1   18      C
2   2015    6   1   2   8   4   L
2   2015    6   1   3   22      C
2   2015    6   1   4   45  4   R
2   2015    6   1   5   26  6   L

CREATE TABLE "tournaments" (
    "tournament"    INTEGER,
    "year"  INTEGER
);

样品:

2   2015    
2   2016    
2   2017    
2   2018    
2   2019

tournaments包含所有理论上可能的数据。实际收集的信息保存在pinsheets中。我想循环tournaments,看看我遗漏了哪些观测。基本上,方法如下:

  • 获取锦标赛/年份组合
  • 检查第{1,2,3,4}轮是否存在pinsheets中的锦标赛/年份/轮组合

我的失败尝试:

SELECT *
  FROM tournaments t
  WHERE NOT EXISTS (
    SELECT *
    FROM pinsheets pin
    WHERE  t.tournament = pin.tournament
    AND t.year = pin.year 
    AND (pin.round = 1 
            OR pin.round = 2
            OR pin.round = 3
            OR pin.round = 4)
            )

所需输出:

tournament   year   round
2   2015    3
2   2016    2
2   2017    2
fnx2tebb

fnx2tebb1#

您需要将tournamentsrounds的所有可能值进行CROSS联接(可以通过CTE获得):

WITH rounds(round) AS (VALUES (1), (2), (3), (4))
SELECT t.tournament, t.year, r.round
FROM tournaments t CROSS JOIN rounds r
WHERE NOT EXISTS (
  SELECT *
  FROM pinsheets p
  WHERE (p.tournament, p.year, p.round) = (t.tournament, t.year, r.round)
);

或者,使用LEFT联接到pinsheets

WITH rounds(round) AS (VALUES (1), (2), (3), (4))
SELECT t.tournament, t.year, r.round
FROM tournaments t CROSS JOIN rounds r
LEFT JOIN pinsheets p
ON (p.tournament, p.year, p.round) = (t.tournament, t.year, r.round)
WHERE p.tournament IS NULL;

请参阅demo

相关问题