简体   繁体   English

mysql where条件基于左联接字段

[英]mysql where condition based on left join field

I am working on a logic where If the LEFT joint field is null then a condition in Where should not be applied. 我正在研究一个逻辑,如果LEFT联合字段为null,则不应应用Where中的条件。 Can some one give me an idea how can It be done with only query. 有人可以告诉我如何仅通过查询来完成。

I tried using IF CASE but its not helping, 我尝试使用IF CASE,但没有帮助,

Query: 查询:

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

When ta.id_c is null, the condition in where AND tb.deleted=0 shouldnt taken in to account. ta.id_c为null时, 不应考虑AND tb.deleted = 0的条件。

Why? 为什么? Because when there is a null value in the linking ID there is no selection of data for the query. 因为当链接ID中的值为空时,将没有查询数据的选择。 Any help? 有什么帮助吗? thanks in advance. 提前致谢。

Expected result: Select columns of the tables. 预期结果:选择表的列。

Actual Table: 实际表:

tableA: tableA:

id_c    sales  
   1    Closed 
   2    Closed 

tableB: tableB:

   id  deleted 
   1    0 

After Query: Current 查询后:当前

id_c    sales   id  deleted 
   1    Closed  1   0

EXPECTED 预期

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

Note: I cannot able to edit the LEFT JOIN conditions 注意:我无法编辑LEFT JOIN条件

Given 给定

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)

or a little less wordy 或少一点罗word

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

results in 结果是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM