如何通过where子句替换左联接中的条件?

问题描述 投票:-1回答:2

[尝试使用where子句而不是左联接来获得相同的结果

TableA模式:

id
name
created_by

TableB模式:

id 
name
updated_by

样本表A

id  name    created_by
1   pen      a
2   paste    k

样本表B

id  name        updated_by
1   inkpen      b
1   ballpen     c

使用left连接进行查询

select tablea.id, tableb.id, tablea.name, tableb.name
from tablea
    left join tableb on tableb.id = tablea.id and tableb.updated_by = 'a'

结果

tablea.id       tableb.id       tablea.name     tableb.name
    1            NULL               pen           NULL

使用where子句进行查询:

select tablea.id, tableb.id, tablea.name, tableb.name
from tablea left join tableb
ON tableb.id = tablea.id WHERE tableb.updated_by = 'a'

结果

tablea.id       tableb.id       tablea.name     tableb.name
    NULL             NULL           NULL              NULL

我们在传递user_id之前使用了一个函数。该函数依次返回一个表,并在左联接中使用了user_id。由于该函数未使用索引,因此我们决定使用视图。但是,在视图中,我们不能传递变量。因此,我们无法在Left join中使用tableb.updated_by,因此在where子句中尝试了相同的查询。

我们如何编写查询,以便通过where子句获得与左联接相同的结果?

mysql sql postgresql-9.4
2个回答
0
投票

如何编写查询,以便通过where子句获得与左联接相同的结果?

你不能。

ONLEFT JOIN子句中的条件,当未满足时,将第一个表的行与空值连接,以替换第二个表中的行。如果这些条件出现在WHERE子句中,则它们在未满足时会排除第一行。有效地将您的LEFT JOIN转换为普通的内部JOIN


0
投票

每当您在where子句中使用Left联接表时,它将左联接的行为转换为内部联接。

如果您正在使用Left join + Where子句查找相同的行为,请尝试这样

select tablea.id, tableb.id, tablea.name, tableb.name
from tablea 
left join tableb ON tableb.id = tablea.id 
WHERE tableb.updated_by = a OR tableb.updated_by is NULL
© www.soinside.com 2019 - 2024. All rights reserved.