我的脚本有问题,需要选择我所有的帖子和相关评论。现在我有以下查询:
$sql = "SELECT posts.post_title, posts.post_modified, post_content,update_modified, update_content
FROM posts
LEFT JOIN updates
ON posts.post_ID = updates.update_post_ID";
查询工作很棒,除了如果帖子有多个评论,它给了我多个条目。我已经搜索了,但不幸的是,我不能重新编写我的查询我的需要。我真的希望有人能帮帮我。
我认为您需要DISTINCT关键字,用作SELECT DISTINCT ...
以避免重复。但是,如果我理解正确,您的评论在更新表中,并且您正在将update_modified
和update_content
拉入您的记录集中。所以假设这些是(潜在的)唯一值,那么DISTINCT将不会将它们分解。最好只使用DISTINCT提取updates.update_post_ID
,然后根据需要时检索的id从更新中提取所需的任何内容。
如果你想每篇文章只返回一行,包含所有的评论,最简单的方法是使用GROUP_CONCAT()
。这将返回所有列数据的csv。假设update_content
是帖子评论,请尝试-
SELECT posts.post_title, posts.post_modified, post_content, GROUP_CONCAT(update_modified), GROUP_CONCAT(update_content)
FROM posts
LEFT JOIN updates
ON posts.post_ID = updates.update_post_ID
GROUP BY updates.update_post_ID
注—GROUP_CONCAT()
的group_concat_max_len
默认值为1024。如果您的注释变得太长,您将需要在运行GROUP_CONCAT()
查询之前增加这个长度,否则注释将被截断-
SET [GLOBAL | SESSION] group_concat_max_len = 10240; // must be in multiples of 1024
SELECT id, name
GROUP_CONCAT(comment) AS comment
FROM table
GROUP BY name;
您还需要注意max_allowed_packet
,因为这是您可以将var_group_concat_max_len
设置为的限制。