gpt4 book ai didi

php - 在 PHP 中对表中的数据进行分组

转载 作者:行者123 更新时间:2023-11-29 04:32:38 25 4
gpt4 key购买 nike

我有一个这样的表sql

post_id    point    user_id
5 1.0 1
6 1.5 1
7 0.0 2
8 1.5 3
9 1.0 3
...

我想将数据打印到这里(按 user_id 对帖子进行分组)

user_id        post_id(point)                     total point
1 5(1.0) | 6(1.5) | ... 2.5
2 7(0.0) | | ... 0.0
3 8(1.5) | 9(1.5) | ... 3.0
...

我试过这样的,但它返回数组

SELECT * FROM table WHERE post_id = ?

如果这是一个愚蠢的问题,我很抱歉,但我是 MySQL 的新手

最佳答案

GROUP BY user_id 中运行查询。使用 GROUP_CONCAT()CONCAT() 生成您的积分/帖子列。 CONCAT() 将字符串放在一起形成 postID (points) 格式,GROUP_CONCAT() 将所有按该组分组的值(在在这种情况下,user_id) 变成一个由分隔符 | 分隔的字符串。

SELECT user_id, 
GROUP_CONCAT(CONCAT(post_id, '(', points, ')') SEPARATOR ' | ') as point_id_posts,
SUM(points) as totalPoint
FROM table
GROUP BY user_id

关于php - 在 PHP 中对表中的数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55630739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com