Php MYSQL使用GROUP BY和ORDER BY返回奇怪的结果
尝试做一个论坛系统优化,在一个查询中选择所有最后的海报,并将它们存储在一个数组中。问题是数据库正在返回非预期的结果 PHP版本5.3.13 MySQL版本5.1.63Php MYSQL使用GROUP BY和ORDER BY返回奇怪的结果,php,mysql,Php,Mysql,尝试做一个论坛系统优化,在一个查询中选择所有最后的海报,并将它们存储在一个数组中。问题是数据库正在返回非预期的结果 PHP版本5.3.13 MySQL版本5.1.63 $getPosts = $dB->fetch(' SELECT post_id, post_poster_id, post_topic_id, post_time, COUNT(post_id) as count FROM forum_posts WHERE post_topic_id IN (
$getPosts = $dB->fetch('
SELECT
post_id, post_poster_id, post_topic_id, post_time,
COUNT(post_id) as count
FROM forum_posts
WHERE post_topic_id IN (
SELECT topic_id
FROM forum_topics
WHERE topic_forum_id = ' . $forum_id . '
)
GROUP BY post_topic_id
ORDER BY post_time DESC
');
foreach($getPosts as $lastPoster)
{
$lastPosts[$lastPoster['post_topic_id']] = $lastPoster;
}
您期望得到什么?请发布示例数据和所需输出。请详细说明。你所说的意外结果是什么意思?Group by将按
post\u topic\u id
@user1486625将行分组欢迎使用StackOverflow!请确保您的问题中包含了所有相关信息,数据库返回了非预期的结果
并不能真正帮助我们回答问题,因为您没有告诉我们您得到了什么,为什么这是意外的,以及您期望的是什么。请在您的问题中添加更多信息,并请尽快查看,以便您了解我们对您的期望以及您对我们的期望。对于SQL问题,提供组也总是有帮助的。部分分组通常会产生“意外”结果。例如,GROUP BY
子句中未指定的列不会按“预期”的方式排序。
SELECT
p.post_id, p.post_poster_id, p.post_topic_id, p.post_time, l.count
FROM forum_posts AS p
-- joining with list of latests in a derived table
INNER JOIN
-- getting latest time and count
(SELECT p.post_topic_id, MAX(post_time) AS post_time, COUNT(post_id) AS count
FROM forum_posts AS p
-- filtering forum_id with join, join is usually preferrable than subquery
INNER JOIN forum_topics AS t ON t.topic_id = p.post_topic_id AND t.topic_forum_id = '$forum_id'
GROUP BY post_topic_id)
AS l USING(post_topic_id, post_time)
-- grouping to strip possible post_time-in-one-topic-duplicates
GROUP BY p.post_topic_id