簡體   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