我正在创建一个论坛,需要一些反馈。我已经编程了很长时间,但是我对 MySQL 相当了解,并且想知道我是否正确地执行了此操作。
这是我用来输出选定论坛的主题索引的查询。我试图在一个查询中收集所有信息,而不是只收集主题信息,然后在每个循环中收集一次帖子和成员信息,总共有 35 个单独的查询(每个主题一个)。明白了吗?
基本上,它有效。即使只有 300-400 个主题,它也有点慢(大约 1 秒)。
我使用了分析,并收集到最耗时的操作是:复制到 tmp 表:0.538037 发送数据:0.206218 复制到组表:0.137549
编辑:每次有人进入页面时查询将运行一次(根据站点活动判断,每小时大约 200-300 次)。我打算一次检索大约 4000-5000 行。
我的问题是:这是最好的方法吗?我可以做些什么来优化这个查询吗?或者在循环中执行大量较小的查询会更好吗?
$user_id: id of the user
$forum_id: id of the selected forum
SELECT
# Topic records
`topics`.*,
# First Post
GROUP_CONCAT(`posts`.`id`) AS `post_id`, # All post ids
`posts`.`post` AS `post_first_msg`,
`posts`.`date` AS `post_first_date`,
`posts`.`member` AS `post_first_member`,
# First member
`members`.`id` AS `member_id`,
`members`.`username` AS member_username,
# Returns last 3 members' id
SUBSTRING_INDEX(
GROUP_CONCAT(`members`.`id` ORDER BY `posts`.`date` DESC SEPARATOR '\\\\'), '\\\\', 3
) AS member_last_id,
# Returns last 3 members' username
SUBSTRING_INDEX(
GROUP_CONCAT(`members`.`username` ORDER BY `posts`.`date` DESC SEPARATOR '\\\\'), '\\\\', 3
) AS member_last_username,
# Get last viewed topic id
`member_topic_lastview`.`lastview` AS `lastview`
FROM
`topics`
# Returns the `posts` table in ASC order
JOIN (
SELECT *
FROM `posts`
ORDER BY `posts`.`date` ASC
) AS `posts` ON `posts`.`topic` = `topics`.`id`
# Member table, only the columns needed
JOIN (
SELECT
`members`.`id`,
`members`.`username`
FROM `members`
) AS `members` ON `members`.`id` = `posts`.`member`
# Forum table, containing the forum info
LEFT JOIN `forum` ON `forum`.`id` = `topics`.`forum`
# Table containing the latest viewed post id of each topic
LEFT JOIN (
SELECT *
FROM `member_topic_lastview`
WHERE `member_topic_lastview`.`member` = '$user_id'
) AS `member_topic_lastview` ON `member_topic_lastview`.`topic` = `topics`.`id`
WHERE
`forum` > $forum_id
GROUP BY
`topics`.`id`
ORDER BY
`topics`.`sticky` DESC,
MAX(`posts`.`date`) DESC
LIMIT 35
非常感谢!