表 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
上面的查询所做的是阻止我在表 1 中检索带有 map_id = 3
的记录。
如果记录存在于表 2 中,我如何实现这一点以及“is_deleted 检查”。
提前致谢。
最佳答案
您需要将 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
中具有 is_deleted=0
的行,并且您仍将返回 table1
中的所有行> 其中 reg_id=5
。
关于mysql - 在 mysql 中的左连接查询中需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17300330/