大家好,我目前有一个运行良好的 MySQL 查询,但我唯一不喜欢的是,当我获得返回的数据时,有些行会重复,除了该行的最后一列。
我想这是因为当我选择包括左连接在内的所有内容时,commenttext
列包含用户提交的帖子的数据。
例如)如果我发布了一个 ID 为 1 的帖子,并且有 5 个人对该帖子发表评论 MySQL 查询将显示 5 行,每列中的所有数据都相同,除了最后一列包含与邮政。
到目前为止,这是我的 MySQL 查询。我怎样才能让它不带回重复的数据,而只带回与帖子 ID 分组的评论,或者我如何将所有评论存储到一个数组中,这样当我运行 foreach 循环时,我就可以运行评论数组里面有一个 while 循环。我使用 foreach 循环的原因是用 html 导出数据。
SELECT
b.id
, b.from_user
, b.dateadded
, b.posttype
, b.posttext
, b.photoname
, b.blahchoice
, b.commentschoice
, b.mood
, c.defaultphoto
, d.firstn
, d.lastn
, e.status
, f.topostid
, f.commenttext
FROM
t_board b
INNER JOIN
t_userprofiles c ON b.from_user = c.user_id
INNER JOIN
t_users d ON b.from_user = d.id
INNER JOIN
t_friendship e ON e.friend_ids = b.from_user
LEFT JOIN
t_postcomments f ON f.topostid = b.id
WHERE
e.status = 'Friend'
AND e.user_ids = :id
ORDER BY
b.id DESC
最佳答案
一种方法是 group_concat()
注释,当你在循环中运行 explode()
注释,然后执行 foreach
显示id下的评论
SELECT b.id,
b.from_user,
b.dateadded,
b.posttype,
b.posttext,
b.photoname,
b.blahchoice,
b.commentschoice,
b.mood,
c.defaultphoto,
d.firstn,
d.lastn,
e.status,
f.topostid,
group_concat(f.commenttext) as commenttext
FROM t_board b
INNER JOIN t_userprofiles c ON b.from_user = c.user_id
INNER JOIN t_users d ON b.from_user = d.id
INNER JOIN t_friendship e ON e.friend_ids = b.from_user
LEFT JOIN t_postcomments f ON f.topostid = b.id
WHERE e.status = 'Friend'
AND e.user_ids = :id
group by b.id
ORDER BY b.id DESC
请注意,当您在 PHP 上执行查询时,commenttext
将全部以逗号分隔,并在循环内为每个 b.id
获取数据,您将拥有所有该 id 的注释为逗号分隔的字符串,您可以分解它以生成另一个数组并显示它们。
此外,您的一些评论中可能包含逗号,因此您可能需要为 group_concat 提供分隔符,如下所示,或者可以选择任何自定义运算符。
group_concat(f.commenttext SEPARATOR '||' ) as commenttext
并用||展开数据
NOTE : The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024 http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
关于php - 如何删除重复的列和组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23886276/