2017-01-22 4 views
1

私はMySQLのテーブルにフォローを複数の行を持っている:複数の行を1つの行に結合するための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 | 

は今、私は次の内容を取得したい:status=0successcountとき

| time  | total | success | failed | buffer | 
+------------+--------+---------+--------+--------+ 
| 2017/01/22 | 555555 | 333333 | 111111 | 123456 | 
| 2017/01/21 | 666666 | 444444 |  0 | 234567 | 

私はtotalidとしてtimeを使用するには、countですstatus=1,failedstatus=-1のときcountbufferのときsizeのときstatus=1

私はどのようにMySQL文を書く必要がありますか?

答えて

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