[英]how to join two tables on common attributes in mysql and php?
我有2張桌子:
table1
id message user
1 testing 23
2 testing again 44
3 test.. 23
5 lol 12
6 test.. 6
和
table2
id user friend
1 23 44
2 23 6
3 19 12
4 23 32
5 23 76
6 23 89
我試圖獲得23
朋友的所有用戶的messages
,包括23
喜歡:
id message user id user friend
1 testing 23 n n n
2 testing again 44 1 23 44
3 test.. 23 n n n
6 test.. 6 2 23 6
我們可以看到12
失蹤了,因為他不是23
朋友,只有19
我有這個
SELECT *
FROM table1 AS w
INNER JOIN table1 AS f ON w.user = f.friend
WHERE (w.user = 23)
但是如果23
有消息但沒有朋友,它將返回null,這也將返回其他23
朋友,如76 and 89
沒有消息..
:)困惑?
有任何想法嗎?
謝謝
這樣的事情應該可以解決問題,盡管內部查詢可能需要稍微修改一下。
SELECT table1.*, table2.*
FROM table1
INNER JOIN
(
SELECT *
FROM table2
WHERE user = 23 or friend = 23
)
AS table2 ON table1.user = table2.user;
問題在於你正在使用INNER JOIN而不是LEFT / RIGHT加入
內聯接返回結果,在您查詢的兩個表上都有寄存器,因此如果用戶沒有任何朋友,它將不會出現在結果上,與消息相同。
您可以在http://en.wikipedia.org/wiki/Join_(SQL )中找到有關不同類型連接的更多信息。
嘗試這個:
SELECT
table1.*,
table2.*
FROM
table2
RIGHT JOIN table2
ON table2.friend = table1.user
WEHRE
table2.user = 23
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.