找不到@previousEndTime
变量仅具有YEAR
值的原因。如何设置一个MySQL变量的时间戳?
我TEST_TABLE样本数据:
| id | name | start | end |
|----|--------|---------------------------|---------------------------|
| 2 | test 1 | January, 01 2016 12:00:00 | January, 01 2016 13:00:00 |
| 3 | test 1 | January, 02 2016 11:00:00 | January, 02 2016 12:00:00 |
| 5 | test 1 | January, 03 2016 15:00:00 | January, 03 2016 16:00:00 |
| 6 | test 2 | January, 01 2016 10:00:00 | January, 01 2016 11:00:00 |
| 7 | test 2 | January, 02 2016 17:00:00 | January, 02 2016 18:00:00 |
SELECT
id,
name,
@previousEndTime,
@previousEndTime := end
FROM
test_table, (SELECT @previousEndTime := 0) var
ORDER BY name, id;
当前结果:
| id | name | @previousEndTime | @previousEndTime := end |
|----|--------|------------------|-------------------------|
| 2 | test 1 | 0 | 2016-01-01 13:00:00 |
| 3 | test 1 | 2016 | 2016-01-02 12:00:00 |
| 5 | test 1 | 2016 | 2016-01-03 16:00:00 |
| 6 | test 2 | 2016 | 2016-01-01 11:00:00 |
| 7 | test 2 | 2016 | 2016-01-02 18:00:00 |
预期结果:
| id | name | @previousEndTime| @previousEndTime := end |
|----|--------|---------------------|-------------------------|
| 2 | test 1 | 0 | 2016-01-01 13:00:00 |
| 3 | test 1 |2016-01-01 13:00:00 | 2016-01-02 12:00:00 |
| 5 | test 1 |2016-01-02 12:00:00 | 2016-01-03 16:00:00 |
| 6 | test 2 |2016-01-03 16:00:00 | 2016-01-01 11:00:00 |
| 7 | test 2 |2016-01-01 11:00:00 | 2016-01-02 18:00:00 |
请检查该FIDDLE
注:
其他方式,我已经试过:
@previousEndTime := CONCAT('',end,'')
@previousEndTime := TIMESTAMP(CONCAT('',end,''))
谢谢里诺。 \t 是这样的:在初始化部分变量的数据类型是确定的? –
是的,我说得对。看一下[User-Defined Variables](http://dev.mysql.com/doc/refman/5.7/en/user-variables.html)。 – Blank