我试图确定某位用户是否喜欢过帖子,但我收到了重复的结果...我是否遗漏了某些内容,或者是否有更好(更有效)的方法来检索此数据?
SELECT
p.*,
u.firstname,
u.lastname,
l.post_id AS liked
FROM `posts` p
LEFT JOIN `users` u ON u.id = p.author_id
LEFT JOIN `likes` l ON l.user_id = p.author_id
WHERE p.author_id=1 AND p.published = 1
ORDER BY p.post_date DESC LIMIT 0, 10
MySQL表:
**users table**
id, firstname, lastname
**posts table**
id, author_id, post, published, post_date
**likes table**
id, post_id, user_id, timestamp
这是输出:
id, author_id, post, firstname, lastname, liked
"36","1","sdfsdf","John","Smith","36"
"36","1","sdfsdf","John","Smith","4"
"27","1","xcvxvc","John","Smith","36"
"27","1","xcvxvc","John","Smith","4"
"29","1","sdfsdf","John","Smith","36"
"29","1","sdfsdf","John","Smith","4"
"3","1",""fdgdfg","John","Smith","36"
"3","1",""fdgdf","John","Smith","4"
"28","1","data","John","Smith","36"
"28","1","data","John","Smith","4"
有什么想法吗?
答案 0 :(得分:1)
我没有意识到你可以在JOIN上使用条件语句,所以我最终这样做是为了解决我的问题:
SELECT
p.*,
u.firstname,
u.lastname,
l.post_id AS liked
FROM `posts` p
LEFT JOIN `users` u ON u.id = p.author_id
LEFT JOIN `likes` l ON l.user_id = p.author_id
AND l.post_id = p.id
WHERE p.author_id=1
AND p.published = 1
ORDER BY p.post_date DESC LIMIT 0, 10
答案 1 :(得分:0)
您有一个典型配置,用于定义posts
和users
之间的多对多关系。但是,有一种特殊的方法可以使用您没有完成的交集表likes
将这些表连接在一起。
交集表包含两个外键,两个表中的每一个都相互关联。在likes
的情况下,这是分别引用users
表和posts
表的user_id和post_id字段。要正确连接这些表,likes
使用user_id字段加入users
表,使用post_id字段加入posts
表。
表格的顺序对于解决关系并不重要。在您的情况下,因为您希望列出所有帖子,即使没有"喜欢"与它们相关联,然后posts
表首先出现。但是,交叉表从不会持续到最后。它必须位于两个实体表之前,或者在列表中位于它们之间。每个实体表都连接到交集表,而不是相互连接。
像这样:
SELECT p.*, u.firstname + ' ' + u.lastname AS LikedBy
FROM `posts` p
LEFT JOIN `likes` l
ON l.post_id = p.id
LEFT JOIN `users` u
ON u.id = l.user_id
WHERE ...