【问题标题】:select * in table_a left join table_b when certain_field is null in table_bselect * in table_a left join table_b when certain_field is null in table_b
【发布时间】:2019-11-09 12:59:18
【问题描述】:

table_a 包含所有订单,而 table_b 仅包含特殊订单。每个表中的每个订单都有一个 code_field。 table_b 中的所有订单也在 table_a 中,但当然不是 table_a 中的所有订单也在 table_b 中。我需要提取 table_a 中不在 table_b 中的所有订单。正在寻找解决方案,但我实际上无法弄清楚如何编写它。

【问题讨论】:

  • 请分享表结构、示例输入数据、预期输出数据以及您当前的尝试 - 这有助于其他人了解您的问题

标签: mysql select left-join


【解决方案1】:

您可以从table_a 中选择所有内容,然后通过code_field 左加入table_b,并且在table_b 中没有匹配顺序的任何地方,字段将为空

SELECT table_a.*
FROM table_a
LEFT JOIN table_b
  ON table_a.code_field = table_b.code_field
  AND table_b.id IS NULL

【讨论】:

  • 什么是“table_b.id”的“id”?也许是行 ID?
  • @gab 只是来自table_b的非空字段
【解决方案2】:

你可以用 NOT EXISTS 做到这一点:

SELECT *
FROM table_a
WHERE NOT EXISTS (
  SELECT 1 FROM table_b
  WHERE table_a.code_field = table_b.code_field
)

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2021-11-29
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 2012-07-20
    相关资源
    最近更新 更多