繁体   English   中英

SQL左连接带子句的右表

[英]SQL left join with clause where on right table

我需要在具有多个条件的数据库上请求客户。

在我的数据库中,我有3个表

客户:

id
nom
prenom
...

联系 :

id
valeur
customer_id

根据我的要求,我有:valeur

这是请求:

select client0_.id as id1_6_
from client client0_ 
inner join entite entite1_ on client0_.entite_id=entite1_.id 
left outer join client_adresse clientadre2_ on     (clientadre2_.client_id=client0_.id) 
left outer join client_contact clientcont3_ on (clientcont3_.client_id=client0_.id) 
where (entite1_.numero_licence in ('ZB230EC')) 
and (upper(client0_.nom) like ('%'||upper('')||'%')) 
and (client0_.prenom is null or upper(client0_.prenom) like ('%'||upper('')||'%')) 
and (clientcont3_.valeur like ('%'||'@mail'||'%')) 
and (client0_.date_creation_sys is null or client0_.date_creation_sys>='2017-01-01') 
and (client0_.date_modification_sys is null or client0_.date_modification_sys>='2017-01-01') 
and (client0_.date_suppression is null or client0_.date_suppression>='9999-12-12')

此请求还给我还没有联系过的客户,我的请求又请联系“ valeur”的客户包含“ @mail”

样本数据

顾客

id  | nom     | prenom 
375 | aurelie |  lilie
389 | t(      | 

接触

id    |  valeur             | customer_id
2740  |  aurelie@mail.com   |  375
2739  |  06 06 06 06 06     |  375

如果我通过搜索启动请求:

    contact.valeur like '%@mail%'
and customer.nom like '%%'

我的结果还可以

但是用:

    contact.valeur like '%%'
and customer.nom like '%t(%'

我没有结果

你能帮助我吗?

有一些片段可以解释这一点:

  • 首先,您要对这些表进行左连接,因此,在contact / address表中是否包含数据不会减少输出中的记录数。
  • 如果由于应用了过滤器而等待接收任何内容,则必须知道在联接条件下过滤表的行为与在where条件下过滤表的行为不同:
    • 联接中应用的过滤器:在继续联接表之前完成过滤器
    • 过滤器应用在何处:过滤器是在连接表之后完成的

因此,如果您什么也不想得到,只需将“连接部分”中的过滤器移至“位置部分”即可。

编辑答案

只是为了解释我的评论...

with customer as (
  select 375 as id, 'aurelie' as nom, 'lilie' as prenom union all
  select 389, 't(', null
),
contact as (
  select 2740 as id, 'aurelie@mail.com' as valeur, 375 customer_id union all
  select 2739, '06 06 06 06 06', 375
)
select *
from customer cs
  left join contact c
    on cs.id=c.customer_id
where c.valeur like '%%'
  and cs.nom like '%t(%'

这没有返回任何值,因为您正在将NULL与like '%%'进行比较

如果where c.valeur is null where c.valeur like '%%'替换为where c.valeur like '%%' ,则将获得您要查找的记录。 如果要继续使用where c.valeur like '%%'始终where c.valeur like '%%'这样的位置,则需要将null转换为某些字符串,例如where isnull(c.valeur,'') like '%%'的空字符串。它也应该工作。 希望对您有所帮助,您可以从这里进行测试

暂无
暂无

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

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