如何在两个值上加入两个表?
select cases.*
from client_cases
inner join cases on client_cases.id = cases.timeline
left join customers on client_cases.customer_id = customers.id or customers.email = 'test@gmail.com'
where cases.timeline in (
select timeline from cases where cases.payload -> 'person' ->> 'phone' ~ '4625152'
)
如果customers.email =' test@gmail.com',我试图获得结果。或者,如果cases.payload JSONB电话字段的值为' 4625152'
如果电话号码匹配,上述查询将仅返回结果。如果电子邮件中没有匹配且电话号码不匹配,则不会。
答案 0 :(得分:2)
我认为将电子邮件条件放在WHERE子句中会更有意义。
select cases.*
from client_cases
inner join cases on client_cases.id = cases.timeline
left join customers on client_cases.customer_id = customers.id
where cases.timeline in (
select timeline from cases where cases.payload -> 'person' ->> 'phone' ~ '4625152'
) or customers.email = 'test@gmail.com'
答案 1 :(得分:0)
on
查找匹配行时使用join
子句。
where
子句用于在完成所有连接后过滤行。
您一直在与customers.email = 'test@gmail.com'
进行联接,但是您使用WHERE case.timeline IN..
对其进行了过滤..这说明了您的结果
SELECT cases.*
FROM client_cases
INNER JOIN cases ON (client_cases.id = cases.timeline)
LEFT JOIN customers ON (client_cases.customer_id = customers.id)
WHERE cases.timeline IN (
SELECT timeline
FROM cases
WHERE cases.payload -> 'person' ->> 'phone' ~ '4625152'
) OR customers.email = 'test@gmail.com'