【问题标题】:SELECT, get the invert result from the WHERE on the JOINSELECT,从 JOIN 上的 WHERE 获取反转结果
【发布时间】:2021-11-08 06:07:39
【问题描述】:

我有这个 MySQL 请求,要求所有商店在特定日期开具发票:

SELECT sh__shop.id AS shop_id, sh__shop.name,
       sh__shop_invoice.*
FROM sh__shop 
LEFT JOIN sh__shop_invoice ON sh__shop_invoice.shop_id = sh__shop.id
WHERE sh__shop_invoice.month_commission LIKE "2021-08-01"

但我看不出如何得到逆。所有在特定日期没有发票的商店。我做不到NOT LIKE "2021-08-01"

【问题讨论】:

  • 你为什么不能NOT LIKE?因为你的 LIKE 不包含任何通配符,为什么不做一个基本的比较=
  • 你为什么不能不喜欢?但是,我会改用<>
  • 另外,将 sh__shop_invoice 从 WHERE 移动到 ON 以获得真正的 LEFT JOIN 结果。就像现在一样,您会得到常规的 INNER JOIN 结果。
  • 大概你说的不是所有没有发票的商店,而是所有有发票的商店不是那个日期。为什么要使用 like 来表示相等?
  • 不要使用LIKE作为日期!

标签: mysql sql join where-clause inverse


【解决方案1】:

您可以使用not exists 来实现。

SELECT sh__shop.id AS shop_id, sh__shop.name
FROM sh__shop 
WHERE 
    NOT EXISTS (SELECT * FROM sh__shop_invoice i
            WHERE i.shop_id = sh__shop.id
                  AND i.month_commission LIKE "2021-08-01");

【讨论】:

    【解决方案2】:

    您可以尝试使用左连接,但 nkt 匹配行

    SELECT distnct sh__shop.id AS shop_id
    FROM sh__shop 
    LEFT JOIN sh__shop_invoice ON sh__shop_invoice.shop_id = sh__shop.id
        AND  sh__shop_invoice.month_commission LIKE "2021-08-01"
    WHERE sh__shop_invoice.shop_id is null 
    

    (在您的查询中,您以错误的方式使用左连接,因为在 where 子句中添加左连接列这作为内部连接起作用)

    【讨论】:

      猜你喜欢
      • 2013-01-03
      • 2011-06-28
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2012-05-19
      • 1970-01-01
      相关资源
      最近更新 更多