从PHP表中分组数据

问题描述 投票:1回答:4

我有一个像这样的表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的新手

php mysql mysqli
4个回答
2
投票

运行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

1
投票

我想这会对你有所帮助

SELECT user_id,GROUP_CONCAT(CONCAT(post_id,'(',point,')') SEPERATOR ' | ') as post_points,SUM(point) as total_points FROM table_name GROUP BY user_id

1
投票

这是GROUP BYGROUP_CONCAT()的工作。尝试这样的事情。

(Qazxswpoi)

https://www.db-fiddle.com/f/4sVVgGk6SyEnFE4C3emMp9/0

0
投票

查询以满足您的要求

SELECT user_id,
       GROUP_CONCAT( CONCAT(post_id, '(', point, ')') ORDER BY post_id SEPARATOR ' | ' ),
       SUM(point) 
  FROM tbl
 GROUP BY user_id
© www.soinside.com 2019 - 2024. All rights reserved.