查询未返回预期结果

时间:2016-11-20 14:33:19

标签: mysql

SELECT u.* ,
(select CASE u.ID 
WHEN u.ID in (select RequestedUserID from user_requestes where userID=3)  THEN 0
ELSE 1
END ) AS Accepted
FROM users u 
WHERE u.ID <>3 
and u.id not in (select friends.FriendID 
             from friends 
             where friends.UserID=3 or friends.FriendID=3) 
order by u.Name asc

我正在尝试使用phpmyadmin执行此查询

select RequestedUserID from user_requestes where userID=3

以上查询返回79作为结果

如果我执行原始查询,我发现了这个

enter image description here

接受应为0而不是1

3 个答案:

答案 0 :(得分:1)

您的案例表达中存在错误

CASE u.ID WHEN u.ID in (...)

内容如下:在子查询中查找u.id. Found = true,not found = false。在MySQL中,true = 1,false = 0。

CASE u.ID WHEN <either 1 or 0>

您错误地将用户ID与布尔结果1或0进行比较。

你想要这个:

SELECT 
  u.* ,
  CASE 
    WHEN u.ID in (select RequestedUserID from user_requestes where userID=3) THEN 0
    ELSE 1
  END AS Accepted
FROM ...

顺便说一下:你的朋友子查询中可能存在语义错误,因为你总是返回FriendID。我想那应该是:

and u.id not in 
(
  select case when FriendID = 3 then UserID else FriendID end
  from friends
  where UserID = 3 or FriendID = 3
) 

或只是

and u.id not in (select FriendID from friends where UserID = 3)
and u.id not in (select UserID from friends where FriendID = 3)

答案 1 :(得分:1)

如果你这样写你的查询怎么办?

SELECT
    u.*,
    CASE
        WHEN u.ID IN (select RequestedUserID from user_requestes where userID=3) THEN 0
        ELSE 1
    END AS Accepted
FROM
    users u 
WHERE
    u.ID <>3 
    and u.id not in (
        select
            friends.FriendID 
        from
            friends 
        where
            friends.UserID=3 or friends.FriendID=3
    ) 
order by
    u.Name asc
  • 不要在CASE之前使用SELECT;
  • 如果您选择CASE WHEN ...语法,则必须提供值而不是搜索条件(See MySQL documentation here

答案 2 :(得分:0)

这可能会更好:

SELECT  u.*,
        IF(EXISTS (
                SELECT  *
                    from  user_requestes
                    where  userID = 3
                      AND  RequestedUserID = u.ID ),
           0, 1 ) AS Accepted
    FROM  users AS u
    LEFT JOIN  friends AS f  ON f.FriendID = u.ID
    WHERE  u.ID != 3
      AND  f.FriendID IS NULL
      AND  ( f.UserID = 3  or  f.FriendID = 3 )

请注意,使用EXISTSIN ( SELECT ... )效率更高。同上LEFT JOIN ... IS NULL