论坛mysql加入

时间:2011-09-19 16:26:49

标签: mysql

我想创建一个简单的论坛,我有3个表:

`forum_forum_topic` (
  `id`,
  `forum_slug`,
  `slug`
  ...
)

`forum_user` (
  `id`,
  `role`,
  `email`,
  `pass`,
  `name`
)

`forum_forum_topic_message` (
  `id`,
  `forum_topic_id,
  `forum_slug` ,
  `user_id`,
  `message`,
  `created_at`,
  `updated_at`,
)

我希望获得有关用户信息的所有主题以及该论坛中的最后一篇文章。所以现在我有了这个问题:

SELECT ft . * , u.name
FROM forum_forum_topic ft
LEFT JOIN forum_user u ON u.id = ft.user_id
WHERE ft.forum_slug = "general-discussions"
ORDER BY ft.created_at DESC

现在我获得论坛主题和在一个查询中创建它们的用户(每个主题一行),是否可以获取该主题行中的最后一条消息信息(带有用户信息)? 例如

id  forum_slug              title   status  views   slug    user_id     post_count  created_at  updated_at  name         last_post_id last_post_user_name last_post_time
43  general-discussions     hallo   NULL    0       hallo   11          2           1316445710  0           another_user 5             user               12312411
42  general-discussions     hi      NULL    0       hi      9           6           1316440635  0           user         12            another_user       141414

1 个答案:

答案 0 :(得分:0)

我正在考虑这个解决方案......我没有测试过。无论如何,它可能不是最好的,因为它很慢......

SELECT ft . * , u.name, 
(select message from forum_forum_topic_message where user_id = u.id order by updated_at desc limit 1) as     'last_message'
FROM forum_forum_topic ft
LEFT JOIN forum_user u ON u.id = ft.user_id
WHERE ft.forum_slug = "general-discussions"
ORDER BY ft.created_at DESC

编辑:添加了条件:“其中user_id = u.id”