应该如何组合MySQL语句将多行组合到单行?

时间:2017-01-22 07:19:27

标签: 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 |      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作为idtotal count status=0 success count status=1 failedcount时,status=-1buffersizestatus=1<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script src="pro_pic_crop_mobile/jquery.cropit.js"></script>

那么我应该如何编写MySQL语句?

2 个答案:

答案 0 :(得分:1)

您可以使用自我加入

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

答案 1 :(得分: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
)