Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 应该如何编写MySQL语句以将多行合并为单行?_Php_Mysql - Fatal编程技术网

Php 应该如何编写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 |

我在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 |      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
)