我在表格中有以下几列:
time action
2019-03-03 ticket start
2019-03-04 redirection
2019-03-05 working
2019-03-07 NULL
2019-03-08 NULL
2019-03-11 problem 1 solved
2019-03-14 redirection
2019-03-15 NULL
2019-03-16 ticket closed
我可以将NULL值更改为我想要的任何值(使用IFNULL),这没问题,但是我想将其更改为除NULL之外的最后一个值。因此,该表将如下所示:
time action
2019-03-03 ticket start
2019-03-04 redirection
2019-03-05 working
2019-03-07 working
2019-03-08 working
2019-03-11 problem 1 solved
2019-03-14 redirection
2019-03-15 redirection
2019-03-16 ticket closed
MySQL查询可能吗?谢谢。
答案 0 :(得分:1)
将coalesce()
用于action
,因此当它为null
时,子查询将返回先前的非null
值:
select
t.time,
coalesce(
t.action, (
select action from tablename
where time = (
select max(time) from tablename
where time < t.time and action is not null
)
)
) action
from tablename t
请参见demo。
结果:
| time | action |
| ------------------- | ---------------- |
| 2019-03-03 00:00:00 | ticket start |
| 2019-03-04 00:00:00 | redirection |
| 2019-03-05 00:00:00 | working |
| 2019-03-07 00:00:00 | working |
| 2019-03-08 00:00:00 | working |
| 2019-03-11 00:00:00 | problem 1 solved |
| 2019-03-14 00:00:00 | redirection |
| 2019-03-15 00:00:00 | redirection |
| 2019-03-16 00:00:00 | ticket closed |
答案 1 :(得分:0)
除了@forpas答案(这是一个SELECT查询)之外,如果您希望用最后一个已知的非空值更新NULL值,这就是更新表的方法
UPDATE your_table t1
INNER JOIN (
SELECT action, max(time) time FROM your_table t1 GROUP BY action ORDER BY time DESC
) t2
SET t1.action = t2.action
WHERE t1.action IS NULL AND t2.action IS NOT null AND t1.time > t2.time;
答案 2 :(得分:0)
您还可以使用var这样的subwuery与用户var一起使用:
SELECT
`time`,
if( `action` is NULL , @last_action , @last_action:=action) as action
FROM (
SELECT `time`, `action`
FROM your_table
ORDER BY time ASC
) as tmp
CROSS JOIN ( SELECT @last_action := "FIRST ROW") as init;
如果第一个ROW为空,则输出文本“ FIRST ROW”
简单:https://www.db-fiddle.com/f/h1hWAahprWWDV3dgSVixPX/0
样品
time action
2019-03-03 00:00:00 ticket start
2019-03-04 00:00:00 redirection
2019-03-05 00:00:00 working
2019-03-07 00:00:00 working
2019-03-08 00:00:00 working
2019-03-11 00:00:00 problem 1 solved
2019-03-14 00:00:00 redirection
2019-03-15 00:00:00 redirection
2019-03-16 00:00:00 ticket closed
答案 3 :(得分:0)
因此,只有在时间列上具有唯一索引时,您才想做的事情将起作用。在您的示例中,该日期要求每天只允许输入一次。另一个限制是,第一个条目(最低索引值)具有非NULL值。
您当然可以使用合并,联接或子查询,但是为什么不保持简单?
要获取最后一个非NULL值(或另一个值),只需将if()
函数与用户定义的变量一起使用:
SELECT time, IF(action IS NULL, @action, @action:= action) as action FROM t order by time