2013-06-01 63 views
1

我有一個列表userid和以下和我有一個用戶表用戶名和用戶名。跟隨系統的MySQL查詢

我希望能夠選擇關注用戶4的用戶,但在同一個select查詢中有一列允許調用followornot,如果用戶4不跟隨誰選擇,或者如果用戶4選擇1跟隨選定的用戶。

我有這樣的想法,但它沒有按預期工作。

查詢是如下

SELECT 
    u.username, 
    u.userid, 
    (case when following= '4' then 1 else 0 end) as followornot 
FROM user u inner JOIN followTable f ON f.userid = u.userid 
WHERE f.following = '4' 

樣本記錄:

用戶

╔════════╦══════════╗ 
║ USERID ║ USERNAME ║ 
╠════════╬══════════╣ 
║  1 ║ john  ║ 
║  2 ║ jane  ║ 
║  3 ║ smith ║ 
║  4 ║ paul  ║ 
╚════════╩══════════╝ 

FollowTable

╔════════╦═════════════╗ 
║ USERID ║ FOLLOWINGID ║ 
╠════════╬═════════════╣ 
║  1 ║   2 ║ 
║  4 ║   1 ║ 
║  3 ║   4 ║ 
║  1 ║   4 ║ 
╚════════╩═════════════╝ 

SQLFiddle Link

+0

你爲什麼喊? –

+0

你能否提供一個sqlfiddle與你的表/數據例子? www.sqlfiddle.com – BeNdErR

+0

它的工作方式有什麼意想不到的?神祕的是,你是否只有'followornot' = 1的行?那將是因爲你的'WHERE'子句將查詢結果限制爲'following ='4'',即那些'followornot' = 1的查詢結果。 – nurdglaw

回答

1
SELECT u.*, 
     (d.followingID IS NULL) followornot 
FROM user u 
     INNER JOIN followTable f 
      ON u.userID = f.userID 
     LEFT JOIN followTable d 
      ON u.userid = d.followingID AND 
       d.userID = 4 
WHERE f.followingid = 4 

輸出

╔════════╦══════════╦═════════════╗ 
║ USERID ║ USERNAME ║ FOLLOWORNOT ║ 
╠════════╬══════════╬═════════════╣ 
║  1 ║ john  ║   0 ║ 
║  3 ║ smith ║   1 ║ 
╚════════╩══════════╩═════════════╝ 
0

你爲什麼不折騰是這樣的:

select u.id, f.key_user, key_follower FROM user u INNER JOIN is_following f ON u.id=f.key_user AND f.key_follower=4; 

其中u.id是用戶標識,key_user是is_following中的fk,user_id後跟用戶標識。