找不到@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