我有 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;
问题是你正在使用内部连接而不是左/右连接
内部联接返回的结果在要查询的两个表上都有寄存器,因此如果用户没有任何好友,则结果中不会包含该联接,消息也是如此。
您可以在 http://en.wikipedia.org/wiki/Join_(SQL( 中找到有关不同类型的连接的详细信息
试试这个:
SELECT
table1.*,
table2.*
FROM
table2
RIGHT JOIN table2
ON table2.friend = table1.user
WEHRE
table2.user = 23