Subquery

跨兩個多對一關係查詢對象的存在

  • September 26, 2018

我有三個關係。第一個是“MyObject”,它包含一個整數“value”屬性以及“Config”的外鍵。關係是“多個 MyObjects 到一個 Config”。

“配置”關係基本上只包含一個名稱。最後是“ConfigKV”關係,具有三個屬性:“Config”的鍵、值和外鍵。每個 Config 有多個 ConfigKV。

這是創建數據庫的 SQL 語句:

CREATE TABLE "MyObject" (
 "value" INTEGER NOT NULL,
 "cfg" INTEGER NULL,
 "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
 CONSTRAINT "cfg_fk"
   FOREIGN KEY ("cfg")
   REFERENCES "Config" ("id"));

CREATE TABLE "Config" (
 "name" TEXT NOT NULL,
 "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT);

CREATE TABLE "ConfigKV" (
 "key" TEXT NOT NULL,
 "value" TEXT NOT NULL,
 "cfg" INTEGER NULL,
 "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
 CONSTRAINT "cfg_fk"
   FOREIGN KEY ("cfg")
   REFERENCES "Config" ("id"));

我想查詢所有 MyObjects :

  • 值為 42

  • 其關聯的 Config恰好關聯了兩個 ConfigKV:

    • “Foo”->“酒吧”
    • “法茲”->“巴茲”

除了上面的“完全”部分,我可以通過這個查詢來實現:

SELECT * FROM MyObject
INNER JOIN (
 SELECT * from ConfigKV WHERE key == 'foo' AND value == 'bar'
) as SQ1 on SQ1.cfg == MyObject.cfg
INNER JOIN (
 SELECT * from ConfigKV WHERE key == 'fuz' AND value == 'baz'
) as SQ2 on SQ2.cfg == MyObject.cfg
WHERE MyObject.value == 42;

內連接巧妙地消除了所有沒有關聯所需鍵值映射的 MyObject。但是,我不知道如何排除 MyObjects 的配置具有指定鍵值映射的超集。這裡有什麼想法嗎?

非常感謝!

您可以使用NOT EXISTS子查詢或使用以下命令添加此限制LEFT JOIN / IS NULL

SELECT * FROM MyObject
INNER JOIN (
 SELECT * from ConfigKV WHERE key = 'foo' AND value = 'bar'
) as SQ1 on SQ1.cfg = MyObject.cfg
INNER JOIN (
 SELECT * from ConfigKV WHERE key = 'fuz' AND value = 'baz'
) as SQ2 on SQ2.cfg = MyObject.cfg
WHERE MyObject.value = 42
 AND NOT EXISTS
     ( SELECT 1
       FROM ConfigKV
       WHERE ConfigKV.cfg = MyObject.cfg
         AND NOT ( key = 'foo' AND value = 'bar'
                OR key = 'fuz' AND value = 'baz'
                 )
     ) ;

引用自:https://dba.stackexchange.com/questions/218587