【问题标题】:Need all information of users, posts and comments in one MySql query在一个 MySql 查询中需要用户、帖子和评论的所有信息
【发布时间】: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


【解决方案1】:

你应该试试这个

SELECT
    *
FROM
    posts p
INNER JOIN
    users u
ON
    u.user_id=p.user_id
LEFT JOIN
    comments c
ON
    p.post_id=c.post_id
INNER JOIN
    users uu
ON
    c.user_id=uu.user_id

【讨论】:

  • 结果和我的问题一样。
  • 这是正确的,因为你有 2 个 cmets 到这个帖子
  • 是的,但这不是问题所在。我在结果中有重复的行。查看我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 2021-03-14
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
相关资源
最近更新 更多