【发布时间】:2017-01-20 22:33:05
【问题描述】:
这是我的桌子:
cmets:
# id, user_id, post_id, message, date
'1', '1', '1', 'This is a comment bla bla bla', '2016-09-04 11:36:11'
'2', '1', '1', 'This is another comment bla bla bla', '2016-09-04 11:39:59'
'3', '1', '2', 'This is a first comment', '2016-09-04 16:35:43'
'4', '2', '2', 'Relax my friend', '2016-09-04 16:35:43'
'5', '1', '2', 'Ok, cool.', '2016-09-04 16:36:03'
'6', '3', '1', 'Cool bro', '2016-09-12 17:51:24'
'7', '3', '2', 'OMG! :O', '2016-09-12 17:51:53'
用户:
# id, password, username, photo, background_photo, email, first_name, last_name
'1', 'rqwerr23r2', 'welkdic', 'img/Friends/guy-2.jpg', './../../img/profile-cover.jpg', 'test@test', 'Omarion', 'welkdic'
'2', '23rqw3rq32', 'McBrewk', 'img/Friends/woman-1.jpg', './../../img/profile-cover.jpg', 'test2@test', 'Hillary', 'McBrewk'
'3', 'wer23r23', 'jmorr', 'img/Friends/guy-2.jpg', './../../img/profile-cover.jpg', 'test3@test', 'John', 'Morrison'
和帖子:
# id, user_id, date, type, message, image, shares, likes, comments_count
'1', '1', '2016-09-01 12:09:00', 'uploaded a photo', 'TODAY IS..... beatifull day.', 'img/Post/game.jpg', '0', '0', '2'
'2', '2', '2016-09-04 16:22:11', 'made a post', 'bla bla bla \r\n for bootstrap css hmtl js framework.', '', '0', '0', '3'
这是我的查询:
SELECT *
FROM posts AS p
RIGHT JOIN users AS u ON u.id = p.user_id
RIGHT JOIN comments AS c ON p.id = c.post_id AND u.id = c.user_id
RIGHT JOIN users AS up ON up.id = c.user_id;
我需要一个查询中有关帖子用户和 cmets 的所有信息。现在,在我的结果中,一切看起来都很好,但是在发布表的重复结果中存在一个问题(标记为蓝色 - 位置 nr 2)。我不知道为什么会这样。 HOW IT LOOKS RIGHT NOW
但它应该类似于在下一行位置 nr3 中带有 NULL 字段: SHOULD LOOKS LIKE THAT 已经尝试使用“group by”和“distinct”但没有运气:( 我的结果中需要所有 cmets 用户和帖子
【问题讨论】:
-
右外连接...切换到左外连接,因为大多数人发现它们很难理解。 (“主表左连接附加数据”而不是“附加数据右连接主表”。)
-
Nope with 'left outer join' 没有帮助。我的 cmets 桌子的 3 排被扔掉了。重复行在同一位置:/ 我需要所有帖子、cmets 和用户
标签: mysql sql duplicates distinct