【问题标题】:Perform anti INNER JOIN on two tables对两个表执行反 INNER JOIN
【发布时间】:2019-12-05 20:49:07
【问题描述】:

我想知道是否有一种快速的方法来执行以下操作。据我了解,两个表中存在的字段上的 INNER JOIN 从两个表中返回信息,该表具有该字段及其共同的值。但是,我要做的是返回不符合 INNER JOIN 条件的表行。因此,例如,如果我将表 1 作为

Product     Price
Greens      $2
Beans       $1
Potatoes    $3
Tomatoes    $4

表2为

Product     Quantity
Potatoes    45
Tomatoes    100
Chickens    27
Turkeys     33

我想要输出的是

Product     Price     Quantity
Greens      $2        NULL
Beans       $1        NULL
Chickens    NULL      27
Turkeys     NULL      33

这可能吗?

谢谢!

【问题讨论】:

  • 你没有明确说出你想要什么。所以你不能推理、编码、搜索或询问。使用足够多的单词、句子和对部分示例的引用来清楚完整地表达你的意思。描述结果:说足够多的人可以离开并带着解决方案回来。在给出关系(船舶)/关联或表(基础或查询结果)时,说明其中的一行根据其列值说明了业务情况。当这很清楚时,它将是一两个常见问题解答。请参阅 How to Ask、其他 help center 链接、点击谷歌搜索“stackexchange 作业”和投票箭头鼠标悬停文本。
  • 请在代码问题中给出minimal reproducible example--剪切&粘贴&运行代码;具有期望和实际输出的示例输入(包括逐字错误消息);标签;明确的规范和解释。这包括您可以提供的最少代码,即您显示的代码可以通过您显示的代码扩展为不正常。 (调试基础。)

标签: ms-access inner-join


【解决方案1】:

您可以对每个表使用NOT EXISTS,并将结果与​​UNION ALL 结合起来:

select t1.product, t1.price, null as quantity from table1 as t1
where not exists (select 1 from table2 where product = t1.product)
union all
select t2.product, null as price, t2.quantity from table2 as t2
where not exists (select 1 from table1 where product = t2.product)

【讨论】:

    【解决方案2】:

    您必须使用两个外连接,一个用于没有对应价格的产品(价格为 NULL),一个用于没有对应数量的产品。 我使用了两个单独的查询(每个连接一个)。 接下来,使用 UNION 合并结果。

    SELECT table1.Product, table1.Price, table2.Quantity
    FROM table1
    LEFT JOIN table2 ON table1.Product = table2.Product
    WHERE table2.Quantity IS NULL
    ORDER BY table1.Price DESC
    UNION
    SELECT table2.Product, table1.Price, table2.Quantity
    FROM table1 RIGHT JOIN table2 ON table1.Product = table2.Product
    WHERE table1.Price IS NULL
    ORDER BY table2.Quantity
    

    【讨论】:

      【解决方案3】:

      您可以使用UNIONMINUS 操作来实现它。 (SELECT * FROM t1 UNION SELECT * FROM t2) MINUS SELECT * FROM t1 INNER JOIN t2 ON t1.Product = t2.Product

      【讨论】:

      • MS Access 不支持minus 关键字。
      猜你喜欢
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多