mysql where condition基于左连接字段

时间:2016-12-02 12:35:50

标签: mysql sql logic

我正在研究一个逻辑,如果LEFT联合字段为null,那么不应该应用Where中的条件。有人可以告诉我如何只用查询来完成它。

我尝试使用IF CASE,但没有帮助,

查询:

SELECT *
FROM tableA ta
LEFT JOIN tableB tb ON tb.id = ta.id_c
WHERE ta.sales = 'Closed'
  AND tb.deleted=0

ta.id_c 为空时, AND tb.deleted = 0 的条件不应考虑到帐户。

为什么呢?因为当链接ID中存在空值时,不会为查询选择数据。有帮助吗?提前谢谢。

预期结果: 选择表格的列。

实际表格:

表A:

id_c    sales  
   1    Closed 
   2    Closed 

tableB的:

   id  deleted 
   1    0 

查询后:当前

id_c    sales   id  deleted 
   1    Closed  1   0

预期

id_c    sales   id    deleted 
   1    Closed  1       0
   2    Closed  NULL   NULL

注意:我无法编辑LEFT JOIN条件

1 个答案:

答案 0 :(得分:2)

鉴于

create table tableA (
  id_c integer,
  sales varchar(255)
);

create table tableB (
  id integer,
  deleted bool
);

insert into tableA values (1, 'Closed'), (2, 'Closed');
insert into tableB values (1, 0);

SELECT *
FROM tableA ta
LEFT JOIN tableB tb ON tb.id = ta.id_c
WHERE
  (ta.sales = 'Closed' AND tb.deleted = 0) OR
  (ta.sales = 'Closed' AND tb.id is null)

或少一点罗嗦

WHERE
  (ta.sales = 'Closed') AND (tb.deleted = 0 OR tb.id is null);

导致

id_c    sales   id  deleted 
1   Closed  1   0
2   Closed  NULL    NULL