透视MySQL表并从其他表中获取遗漏的值

olmpazwi  于 12个月前  发布在  Mysql
关注(0)|答案(2)|浏览(152)

有两种MySQL表:

table1

id |  time |  status
-----------------------
1  | 10:00 | conn     | 
1  | 10:01 | disconn  | 
2  | 10:02 | conn     | 
2  | 10:03 | disconn  | 
3  | 10:04 | conn     | 

table2

id |  time |
------------
3  | 10:05 |

字符串
如果某个标识没有断开连接时间值,则从表2中获取该值。要获得所需结果,SQL查询是什么:

id | conn | disconn|
--------------------
1  | 10:00| 10:01  |
2  | 10:02| 10:03  |
3  | 10:04| 10:05  |

14ifxucb

14ifxucb1#

在这种情况下,你可以使用LEFT JOINCOALESCE。下面是示例代码:

SELECT 
    t1.id,
    t1.time AS conn,
    COALESCE(t1_disconn.time, t2.time) AS disconn
FROM table1 t1
LEFT JOIN table1 t1_disconn ON t1.id = t1_disconn.id AND t1_disconn.status = 'disconn'
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t1.status = 'conn'
ORDER BY t1.id;

字符串
下面是示例输出:


的数据
这里是fiddle link

o4tp2gmn

o4tp2gmn2#

或者,您也可以使用GROUP BY而不使用self join,如下所示:

SELECT
    T1.ID,
    MAX(CASE WHEN T1.STATUS = 'conn' THEN T1.TIME END) AS CONN,
    COALESCE(MAX(CASE WHEN T1.STATUS = 'disconn' THEN T1.TIME END), T2.TIME) AS DISCONN
  FROM
    table1 T1
      LEFT JOIN table2 T2 ON T1.ID = T2.ID
 GROUP BY T1.ID, T2.TIME
 ORDER BY T1.ID;

字符串

相关问题