【发布时间】: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=3lastcommentid=2在预期结果中?在我看来是6 -
@Alex - 因为这不是最后一个评论,而是最后一个评论的人。
-
@Baron - 旁注,最近的评论部分称为greatest-n-per-group。这在实际支持窗口函数的 RDBMS 中会更容易。