我正在开展一个项目,我需要在查询中更新2个表。
我这样做
UPDATE ward_beds a, ipd_patient_list b
SET
a.occupation_status = 'empty',
b.patient_status = 'Discharged'
WHERE
a.ward_id = b.ward_id AND b.patient_id = '4'
AND
b.appointment_id = '6' AND b.ward_id = '1'
到目前为止它正在运行,现在我想更新此
b.patient_status = 'Discharged'
在所有匹配行中的最后一行。我试着把这个
ORDER BY b.row_id DESC LIMIT 1
但它显示
#1221 - Incorrect usage of UPDATE and ORDER BY
错误。我该怎么办?
答案 0 :(得分:2)
您不能在此类更新中使用限制 但你可以使用子查询搜索正确的id并加入其他表
UPDATE ward_beds a
INNER JOIN (
select ward_id, max(row_id) last_id
from ipd_patient_list
group by ward_id
) t on t.ward_id = a.ward_id
INNER JOIN ipd_patient_list b ON a.ward_id = b.ward_id
AND b.patient_id = '4'
AND b.appointment_id = '6'
AND b.ward_id = '1'
AND b.row_id = t.last_id
SET a.occupation_status = 'empty',
b.patient_status = 'Discharged'