我在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
为buffer
,size
时status=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语句?
答案 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
)