php - mysql对左表中的空值进行联接查询

标签 php mysql sql join

我有下表

用户表

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 

Here is the demo

您不需要使用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/

相关文章:

php - 某点后 3 列网格断开

php - 无法安装全局宅基地 : Your requirements could not be resolved

php - 将当前行的 ID 附加到数据库表中的图像名称

mysql - 使用存储过程选择查询

php - 如何使用相同的查询插入数据

MySQL 过程返回 0 行

python - 类型错误 : 'int' object does not support indexing

php - Laravel:获取数组元素以显示在表格上

python - 使用 MySQL 和 Python 并发读写(不同进程)的问题

sql - 如何在查询公式中有多个标签?