Mysql 在结果中使用空值左连接和WHERE
一个简单的查询为我提供了user1与其他用户的关系:Mysql 在结果中使用空值左连接和WHERE,mysql,sql,join,left-join,Mysql,Sql,Join,Left Join,一个简单的查询为我提供了user1与其他用户的关系: select u.id, u.name, ur.* from users u left join user_relationships ur on ((ur.source_user_id = 1 and target_user_id = u.id) OR (ur.source_user_id = u.id and target_user_id = 1)) where u.id != 1 ORDER BY u.id; +----+-
select u.id, u.name, ur.*
from users u
left join user_relationships ur
on ((ur.source_user_id = 1 and target_user_id = u.id) OR
(ur.source_user_id = u.id and target_user_id = 1))
where u.id != 1
ORDER BY u.id;
+----+-------+----------+--------+------+
| id | name | rel_from | rel_to | type |
+----+-------+----------+--------+------+
| 2 | beta | 2 | 1 | 2 |
| 3 | gamma | 1 | 3 | 2 |
| 4 | delta | 4 | 1 | 1 |
| 5 | five | NULL | NULL | NULL |
+----+-------+----------+--------+------+
但是我只想要一个与type
的关系不是2('delta'和'five')的用户列表
我尝试了一些方法
-- Approach 1
-- -----------------------------
where
(u.id != 1) AND
(ur.type != 2)
-- gives 'delta', not 'five'
-- Approach 2
-- -----------------------------
left join user_relationships ur
on ((ur.source_user_id = 1 and target_user_id = u.id) OR
(ur.source_user_id = u.id and target_user_id = 1)) AND
(ur.type != 2)
where
(u.id != 1)
ORDER BY u.id;
-- ur.* fields are NULL
-- (all rows, except for 'delta')
-- Approach 3
-- -----------------------------
where
(u.id != 1) AND
((ur.type != 2) OR
(ur.type IS NULL))
-- this works, but why ?
(A) 为什么方法1,2不起作用,而方法3起作用
(B) 有没有其他(或许更优雅的)方法可以达到同样的效果
在处理可能的空值时,应使用IS null比较值
因此,您的位置可能是:
where
(u.id != 1) AND
(ur.type != 2 OR ur.type IS NULL)
卡娅
在处理可能的空值时,应使用IS null比较值
因此,您的位置可能是:
where
(u.id != 1) AND
(ur.type != 2 OR ur.type IS NULL)
这应该会有帮助:谢谢,但这不仅仅是关于
为NULL
。但是为什么方法2不起作用呢?为什么连接不只是处理(type!=2)关系?链接不回答这个问题吗?“您不能使用算术比较运算符,如=,这应该会有帮助:谢谢,但这不仅仅是关于为NULL
。但是为什么方法2不起作用?为什么连接不处理(type!=2)关系?链接不回答这个问题吗?”您不能使用算术比较运算符,如=,