2016-11-20 261 views
0
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

接受s HOULD是0,而不是1

+0

您從不限制原始查詢將「接受」值設置爲零,那麼您爲什麼要這樣做? –

+0

你是什麼意思? – Sora

+0

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查詢 – Strawberry

回答

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
+0

@Thorsten是對的。我遲到了兩分鐘:-)。 –

+0

非常感謝你爲我工作這個工作! – Sora

+0

不客氣:-) –

1

有你的情況表達了一個錯誤

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

內容如下:查找u.id子查詢。找到=真,未找到=假。在MySQL真= 1,假= 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) 
+0

我的目的是看看這位朋友是否存在user_requestes我想設置爲可接受的0否則我需要接受的是1 – Sora

+0

是的,我明白這一點。這是u.id在(...)中做的情況。 'u.id在(...)'中的情況u.id,然而,你做了一些你不想要的東西。 –

+0

呃,......「這個朋友」?你在哪裏子句得到*非朋友*。 –

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) 

注意使用EXISTS爲比IN (SELECT ...)更有效率。同上LEFT JOIN ... IS NULL