MySQL Union和JOIN

时间:2016-11-08 16:23:08

标签: mysql join

我有以下表格

purchase_order         item
------------------     ------------
id (PK)                id (PK)
deleted                deleted
name                   name
                       purchase_order_id (FK)

如何返回链接到未删除的非null purchase_order的所有项目列表,以及没有链接到项目的所有purchase_orders,无论是否已删除。

例如表格

PURCHASE_ORDER

  id    name         deleted
  ---------------------------
  1     Big Sale     0
  2     Other Sale   1
  3     Empty Sale   0

项目

  id    name         deleted  purchase_order_id
  ----------------------------------------------
  1     Fruit        1        1
  2     Bread        0        1
  3     Water        0        2

正确的查询给了我:

po_id name          item_id  name
------------------------------------
1      Big Sale     2        Bread
3      Other Sale   NULL     NULL

编辑:这是我必须达到的地方,但问题是规定i.deleted = 0,它会停止任何未加入项目的行返回

SELECT po.id, po.name, i.id, i.name
FROM purchase_order po
LEFT JOIN item i ON i.purchase_order_id=po.id
WHERE po.deleted = 0 AND i.deleted = 0

1 个答案:

答案 0 :(得分:1)

@strawberry给了我答案

SELECT po.id, po.name, i.id, i.name
FROM purchase_order po
LEFT JOIN item i ON i.purchase_order_id=po.id AND i.deleted = 0
WHERE po.deleted = 0