我有下表
用户表
user_id name location_id status_id
1 test 1 1
2 john NULL 1
3 royi 1 1
4 mahi 2 1
地点表
location_id location_name location_type status_id
1 US 1 1
2 UK 1 1
3 BR 1 1
4 IN 2 1
我想将用户和位置表与 location_id 连接起来并找到空记录。 我已经实现了以下查询,但它不起作用。
SELECT *
FROM user u
left join location l
ON u.location_id = l.location_id
WHERE
u.status_id = 1
and l.status_id = 1
and l.location_type = 1
or u.location_id IS NULL
我期待这样的结果
user_id name location_id status_id location_id location_name location_type status_id
1 test 1 1 1 US 1 1
2 john NULL 1 NULL NULL NULL NULL
3 royi 1 1 1 US 1 1
4 mahi 2 1 2 UK 1 1
当我将 l.location_type 更改为 2 时,预期结果如下
user_id name location_id status_id location_id location_name location_type status_id
2 john NULL 1 NULL NULL NULL NULL
最佳答案
试试这个:
SELECT *
FROM user u
left join location l
ON u.location_id = l.location_id
and l.status_id = 1
and l.location_type = 1
where
u.status_id = 1
您不需要使用u.location_id IS NULL
,因为左连接不会排除用户,它只是在匹配的位置上添加用户的位置。
我发现您编辑了帖子,并将 john 的 status_id 从 2 更改为 1。当然,如果 John 状态 id 为 2,则查询永远无法检索到他(删除 where u.status_id = 1
如果需要)
给我留言,如果预期的输出是错误的,我会尽快修复它。
关于php - mysql对左表中的空值进行联接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23421713/