随着越来越多的人这样做,我将使用短信API向某些人发送有关他们今天约会的提醒。

所以我使用此查询获取数据没有任何问题:

SELECT users.id as userid, consultations.patient_id as patientid, consultations.title as patientname, patients.mphone as phone
FROM users
JOIN consultations
ON users.id = consultations.user_id
JOIN patients
ON consultations.patient_id = patients.id
WHERE users.sms > 0 AND DATE(consultations.start) = (CURDATE() + INTERVAL 1 DAY) AND patients.mphone <> ''


同时,我想更新咨询表并为每个consultations.reminder = true输出的每一行设置substract 1 from users.smsusers.id

我的第一个问题是,如果添加count(),查询将自动分组(或者仅显示最后一行,不确定原因)。

如果您有建议... :)

最佳答案

我的MySQL有点生锈,但是您可以将结果插入到临时表中,然后从那里更新其他表。除此之外,select语句不能修改数据。

尝试这样的事情;

CREATE TEMPORARY TABLE IF NOT EXISTS TempAppointments AS (
SELECT users.id as userid, consultations.patient_id as patientid, consultations.title as patientname, patients.mphone as phone
FROM users
JOIN consultations
ON users.id = consultations.user_id
JOIN patients
ON consultations.patient_id = patients.id
WHERE users.sms > 0 AND DATE(consultations.start) = (CURDATE() + INTERVAL 1 DAY) AND patients.mphone <> '')


UPDATE C
SET reminder = true
FROM consultations AS C INNER JOIN TempAppointments AS T ON C.user_id = T.user_id

UPDATE U
SET sms = (sms - 1)
FROM Users AS U INNER JOIN TempAppointments AS T ON U.user_id = T.user_id


但请记住,请在最后删除临时表。

DROP TEMPORARY TABLE TempAppointments

关于mysql - 同时进行SELECT,JOIN和UPDATE,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36997902/

10-11 04:55