Php 应该如何编写MySQL语句以将多行合并为单行?
我在MySQL表中有多行,如下所示:Php 应该如何编写MySQL语句以将多行合并为单行?,php,mysql,Php,Mysql,我在MySQL表中有多行,如下所示: | time | status | count | size | +------------+--------+--------+--------+ | 2017/01/22 | -1 | 111111 | NULL | | 2017/01/22 | 0 | 555555 | NULL | | 2017/01/22 | 1 | 333333 | 123456 | | 2017/01/21 |
| time | status | count | size |
+------------+--------+--------+--------+
| 2017/01/22 | -1 | 111111 | NULL |
| 2017/01/22 | 0 | 555555 | NULL |
| 2017/01/22 | 1 | 333333 | 123456 |
| 2017/01/21 | 0 | 666666 | NULL |
| 2017/01/21 | 1 | 444444 | 234567 |
现在我想得到以下内容:
| time | total | success | failed | buffer |
+------------+--------+---------+--------+--------+
| 2017/01/22 | 555555 | 333333 | 111111 | 123456 |
| 2017/01/21 | 666666 | 444444 | 0 | 234567 |
我使用time
作为id
,total
是count
当status=0
时,success
是count
当status=1
时,failed
是count
当status=-1
时,缓冲区是size
大小
那么我应该如何编写MySQL语句呢?您可以使用自连接
select a.time, a.count as totale, b.count as success, c.count as failed, b.size as buffer
from my_table as a
left join my_table as b on a.time = b.time and b.status = 1
left join my_table as c on a.time = c.time and b.status = -1
where a.status = 0
您需要使用子查询来获取同一行上的数据。每个子查询搜索特定类型的数据,然后外部查询根据时间将数据连接在一起。这应该满足您的需求:
SELECT success.time, success.count AS success, failed.count AS failed, buffered.count AS buffered
FROM (
(SELECT `count`, `time`
FROM tbl
WHERE `status` = 0) AS success
INNER JOIN
(SELECT `count` `time`
FROM tbl
WHERE `status` = 1) AS failed ON failed.time = success.time
INNER JOIN
(SELECT `count` `time`
FROM tbl
WHERE `status` = -1) AS buffered ON buffered.time = success.time
)