表1:
name | map_id | reg_id
abc | 1 | 5
pqr | 2 | 5
xyz | 3 | 5
表2:
map_id | map_name | is_deleted
1 | map1 | 0
2 | map2 | 0
我的SQL查询:
SELECT *
FROM table1 t1
LEFT JOIN table2 t2
ON t1.map_id = t2.map_id
WHERE t1.reg_id = 5
AND t2.is_deleted = 0
上述查询的作用阻止我在table1中使用map_id = 3
检索记录。
如果记录存在于table2中,如何实现此目的以及'is_deleted check'。
提前感谢。
答案 0 :(得分:3)
您需要将is_deleted
检查移至JOIN:
select t1.name, t1.map_id, t1.reg_id, -- replace select * with columns
t2.map_name, t2.is_deleted
from table1 t1
left join table2 t2
on t1.map_id = t2.map_id
and t2.is_deleted = 0
WHERE t1.reg_id = 5;
见SQL Fiddle with Demo。您当前的查询导致LEFT JOIN
的行为类似于INNER JOIN
,因为您将is_deleted
作为WHERE子句的一部分。如果您将其移至JOIN,那么您将返回table2
的{{1}}行,但您仍会返回is_deleted=0
table1
所有行。