在从mySQL数据库中选择项目时遇到问题

时间:2017-03-30 14:41:16

标签: mysql

表:

User:
ID
gender
looking_for_gender

User_Status:
User_ID1
User_ID2
Status

虽然此选择有效,但我还想选择没有状态的用户。换句话说,我想选择没有身份的所有人或者!=朋友。不知怎的AND& OR没有做到这一点。

目前有效的查询:

SELECT u.* FROM User u
JOIN User_Status us ON u.ID = us.User_ID1
WHERE us.Status != "FRIENDS"
AND us.User_ID2 =4 AND gender ="f"

示例数据User_Status:
User_ID1 ----- User_ID2 -----状态
---- 1 ---------------- 4 ------------ has_send_request
---- 2 ---------------- 4 ------------朋友
---- 3 ---------------- 4 ------------朋友

示例数据用户:
ID
0
1
2
3
4
5个

3 个答案:

答案 0 :(得分:3)

您必须使用or

添加条件“无状态”
WHERE (us.Status != "FRIENDS" or us.status is null) AND us.User_ID2 =4 AND gender ="f"

澄清后更新:

select u.* from user u left join user_status us on u.id = User_ID1 and us.User_ID2 =4  where gender ="f" and (us.Status != "FRIENDS" or us.status is null)

答案 1 :(得分:0)

似乎你找到了NOT子句:

https://www.techonthenet.com/sql/not.php

你可以做类似的事情:

 SELECT u.* FROM User u JOIN User_Status us ON u.ID = us.User_ID1 WHERE status IS NOT NULL

答案 2 :(得分:0)

当你评估null时,你需要使用null,否则它将始终返回false。

SELECT u.*
FROM User u
INNER JOIN User_Status us
    ON u.ID = us.User_ID1
WHERE (us.STATUS != "FRIENDS" OR us.STATUS IS NULL) 
    AND us.User_ID2 = 4
    AND gender = "f"