簡體   English   中英

從同一張表中選擇2行以適應不同的條件

[英]Selecting 2 rows from same table for different criterias

我嘗試了許多內部聯接,外部聯接的示例,甚至嘗試用猜測來迷惑我自己(這常常會奏效),但是在這里沒有運氣。

表1:follower_user_id,followed_user_id

(請注意,它是跟隨者R _和跟隨者D _)

表2:user_id,用戶名

因此,我需要表2中的兩行,其中一個user_id匹配follower_user_id,另一行其中user_id匹配followed_user_id

查詢內的查詢工作正常,但我知道這不是要走的路...

SELECT f.*, u.*
FROM tbl_follows f, tbl_users u
WHERE follower_user_id = u.user_id

這是基本查詢

while($row = $r->fetch_assoc()){
    //here i make another query to get the username of the followed_user_id
}

當然可以在單個查詢中完成嗎?

提前致謝

---更新1:示例數據---

tbl_users

user_id    |    username
--------------------------------------
1          |    abc123
2          |    xyz789
3          |    nosey123

tbl_follows

follower_user_id    |    followed_user_id
-------------------------------------------
3                   |    2                 //nosey123 is following xyz789
3                   |    1                 //nosey123 is following abc123
1                   |    2                 //abc123 is following xyz789

While Resultsecho "$row[username] is following $row['???????']<br />"

我在找:

nosey123 is following xyz789
nosey123 is following abc123
abc123 is following xyz789

你嘗試過這樣的事情嗎?

SELECT f.*, u.*
FROM tbl_follow f
JOIN tbl_users u ON u.user_id = f.follower_user_id OR u.user_id = f.followed_user_id;

這將為每個userID返回兩行,因為對於追隨者用戶將有一個匹配項,而對於跟隨用戶將有一個匹配項。

SELECT DISTINCT(A.user_id), A.username, B.*
FROM tbl_follow A
     JOIN tbl_users B 
          ON B.user_id = A.follower_user_id 
             OR B.user_id = A.followed_user_id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM