mysql如何合并/连接/完成从同一个表中的1行到另一行的信息

时间:2012-12-20 22:06:31

标签: mysql join merge complete

我有一张这样的表

ID   | starttime | endtime  |manualid
1    | 12:24:00  | 13:25:00 |null
2    | null      | null     |1
3    | null      | null     |5
4    | 16:34:00  | 19:25:00 |null
5    | 21:40:00  | 23:25:00 |null

我想要的是SELECT有这样的东西

ID   | starttime | endtime  |searchid
1    | 12:24:00  | 13:25:00 |null
2    | 12:24:00  | 13:25:00 |1
3    | 21:40:00  | 23:25:00 |5
4    | 16:34:00  | 19:25:00 |null
5    | 21:40:00  | 23:25:00 |null

我们的想法是使用他们的id

使用来自其他行的同一表中的信息来完成某些行的信息。

1 个答案:

答案 0 :(得分:0)

我正试图在manualid = id上加入your_table。如果连接失败(因为manualid is null,或者它的id不存在),t2.id将为空。

如果连接不成功,我从原始行中选择starttimeendtime,否则我从另一行中选择它:

SELECT
  t1.ID,
  case when t2.id is null then t1.starttime else t2.starttime end as starttime,
  case when t2.id is null then t1.endtime else t2.endtime end as endtime,
  t1.manualid
FROM
  your_table t1 left join your_table t2 on t1.manualid=t2.id