1

我已经看到了各种各样的例子,但是我找不到一个明确的例子来说明如何在没有给定值的情况下返回所有与行无关table_A的行。我能找到的最接近的匹配是:table_Btable_A_Btable_A.idtable_B.id

  1. 获取A与一个或多个行不相关B但不知道 B 中的哪个值是问题的列表。

  2. 获取A与 given 无关的列表B

  3. 获取A以逗号分隔的无关字段列表B(不确定我是否看到了这一点,但似乎一个示例可以这样扩展)。

  4. A一个s 和s的列表,B彼此不相关,但没有指明哪个不相关。

我还可以获得所有潜在A_B元组的列表:

SELECT A.id, B.id  FROM A
INNER JOIN B ON A.id <> B.id

而且我可以假设对关联表使用一种EXCEPT解决方法(我认为),但是所有尝试都失败了,我想一旦该连接返回了数百万个潜在组合,它的效率无论如何都会低得多。

所以给定表值:

A
id | name
 1 | X
 2 | y
 3 | z


B
id | name
 7 | e
 8 | f
 9 | g

A_B
id | a_id | b_id
 1 |    1 |    7
 2 |    1 |    8
 3 |    1 |    9
 1 |    2 |    7
 2 |    2 |    8
 1 |    3 |    7

是否有会返回的查询:A | 乙 2 | 9 3 | 8 3 | 9

甚至更好:

 A | B 
 y | g
 z | f
 z | g

还是这是自找麻烦?

4

1 回答 1

3

从 A 和 B 之间的交叉连接开始以获得所有可能的对。然后对关系表进行左连接并选择不匹配的位置:

select driver.aID, driver.bID
from (select a.id as aID, b.id as bID
      from table_A A cross join table_B B
     ) driver left outer join
     table_A_B ab
     on ab.aID = driver.aID and ab.bID = bID
where ab.aID is null

这可行,假设 id 永远不会为 NULL。

I haven't tested the SQL so it might have syntax errors.

This version gets you the names:

select driver.aName, driver.bName
from (select a.id as aID, b.id as bID, a.name as aName, b.name as Bname
      from table_A A cross join table_B B
     ) driver left outer join
     table_A_B ab
     on ab.aID = driver.aID and ab.bID = bID
where ab.aID is null
于 2013-03-30T18:51:49.050 回答