我目前正在将数据从一种结构转换为另一种结构,在此过程中,我必须从组中的第一个条目获取一个状态ID,并将其应用于同一组中的最后一个条目。使用硬编码值时,我可以定位并更新组中的最后一个项目,但是尝试使用第一个条目中的status_id时,我遇到了麻烦。这是数据结构的示例。
-----------------------------------------------------------
| id | ticket_id | status_id | new_status_id | created_at |
-----------------------------------------------------------
| 1 | 10 | NULL | 3 | 2018-06-20 |
| 2 | 10 | 1 | 1 | 2018-06-22 |
| 3 | 10 | 1 | 1 | 2018-06-23 |
| 4 | 10 | 1 | 1 | 2018-06-26 |
-----------------------------------------------------------
因此,想法是采用ID 1的new_status_id
并将其应用于ID 4的相同字段。
这是使用硬编码值时有效的查询
UPDATE Communications_History as ch
JOIN
(
SELECT communication_id, MAX(created_at) max_time, new_status_id
FROM Communications_History
GROUP BY communication_id
) ch2
ON ch.communication_id = ch2.communication_id AND ch.created_at = ch2.max_time
SET ch.new_status_id = 3
但是当我使用以下查询时,我得到Unknown column ch.communication_id in where clause
UPDATE Communications_History as ch
JOIN
(
SELECT communication_id, MAX(created_at) max_time, new_status_id
FROM Communications_History
GROUP BY communication_id
) ch2
ON ch.communication_id = ch2.communication_id AND ch.created_at = ch2.max_time
SET ch.new_status_id = (
SELECT nsi FROM
(
SELECT new_status_id FROM Communications_History WHERE communication_id = ch.communication_id AND status_id IS NULL
) as ch3
)
谢谢!
答案 0 :(得分:0)
所以我只是想出了使用变量的方法。原来的“解决方案”只有在表中有一张票证的历史记录时才有效,但是当所有数据都导入后,它就不再起作用。但是,此调整似乎可以解决该问题。
UPDATE Communications_History as ch
JOIN
(
SELECT communication_id, MAX(created_at) max_time, new_status_id
FROM Communications_History
GROUP BY communication_id
) ch2
ON ch.communication_id = ch2.communication_id AND ch.created_at = ch2.max_time
SET ch.new_status_id = ch2.new_status_id;