【问题标题】:MySQL Join Three Tables, Count, and Get The Last UsernameMySQL连接三个表,计数,获取最后一个用户名
【发布时间】:2015-05-23 13:08:51
【问题描述】:

我的 sql 查询有问题。我需要加入三个表,计算行数,获取最后一行,并创建自定义列。 我的表格示例如下:

表名:文章

_______________________________________
idarticle     idwriter     title
---------------------------------------
1             1            Title One
2             3            Title Two
3             2            Title Three

表名:评论

________________________________________________________________________________
idcomment     idarticle     idcommented     content          datetime
--------------------------------------------------------------------------------
1             1             2               Comment One      2015-05-15 00:00:00
2             1             3               Comment Two      2015-05-16 00:00:00
3             1             1               Comment Three    2015-05-17 00:00:00
4             2             2               Comment Four     2015-05-18 00:00:00
5             3             3               Comment Five     2015-05-19 00:00:00
6             3             2               Comment Six      2015-05-20 00:00:00

表名:成员

_____________________
idmember     username
---------------------
1            apple
2            orange
3            banana

如何通过一个查询连接所有表、计数并获取最后评论+用户名。 可能结果如下:

_____________________________________________________________________________________________________________________
idarticle idwriter title       username_writer totalcomments lastcomment_id lastcomment_username lastcomment_datetime
---------------------------------------------------------------------------------------------------------------------
3         2        Title Three orange          2             2              orange               2015-05-20 00:00:00
2         3        Title Two   banana          1             2              orange               2015-05-18 00:00:00
1         1        Title One   apple           3             1              apple                2015-05-17 00:00:00

我希望有人能解决我的问题。 我使用 PHP 5.4、MySQL 5.5 和 MeekroDB 库,因此查询必须支持这些库。 对不起我的英语不好。 谢谢

【问题讨论】:

  • 有 sqlfiddle 吗?
  • 为什么idarticle=3 lastcommentid=2 在预期结果中?在我看来是6
  • @Alex - 因为这不是最后一个评论,而是最后一个评论的人。
  • @Baron - 旁注,最近的评论部分称为greatest-n-per-group。这在实际支持窗口函数的 RDBMS 中会更容易。

标签: mysql sql join count


【解决方案1】:

http://sqlfiddle.com/#!9/132336/1

SELECT a.idarticle, a.idwriter , a.title, 
       m.username, 
       c.idcomment, cm.username, c.datetime
FROM article a
LEFT JOIN member m
ON a.idwriter = m.idmember
LEFT JOIN comment c
ON a.idarticle = c.idarticle
LEFT JOIN comment c1
ON a.idarticle = c1.idarticle
  AND c.datetime<c1.datetime
LEFT JOIN member cm
ON c.idcommented = cm.idmember
WHERE c1.datetime IS NULL

【讨论】:

    猜你喜欢
    • 2012-11-23
    • 2022-12-17
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 2014-01-23
    相关资源
    最近更新 更多