我正在尝试在mysql中运行此查询
UPDATE studentassessment sa SET sa.issubmitted=FALSE WHERE
sa.studentassessmentid <>
(SELECT studentassessmentid FROM studentassessment sa1 WHERE
sa.StudentId=sa1.StudentId
AND sa.AssessmentPeriodId=sa1.AssessmentPeriodId
ORDER BY sa1.studentassessmentid DESC LIMIT 0, 1)
AND sa.studentid=568;
给了我这个错误
您无法在FROM子句
中为更新指定目标表'sa'
我发现了这类问题的数量,但它们是针对他们被问到的查询所特有的,所以对我没什么帮助,从其中一个答案中我试图改变这样的查询
UPDATE studentassessment sa SET issubmitted=FALSE WHERE
sa.studentassessmentid <>
(
SELECT studentassessmentid FROM
(
SELECT studentassessmentid FROM studentassessment sa1 WHERE
sa.StudentId=sa1.StudentId
AND sa.AssessmentPeriodId=sa1.AssessmentPeriodId
ORDER BY sa1.studentassessmentid DESC LIMIT 0, 1
) AS T
)
AND sa.studentid=568;
然后我开始收到此错误
'where子句'中的未知列'sa.StudentId'
任何帮助?
修改
这也行不通
UPDATE studentassessment sa
INNER JOIN
(SELECT studentassessmentid FROM studentassessment sa1 WHERE
sa.StudentId=sa1.StudentId
AND sa.AssessmentPeriodId=sa1.AssessmentPeriodId
ORDER BY sa1.studentassessmentid DESC LIMIT 0, 1) T
ON sa.studentassessmentid<>T.StudentAssessmentId
SET sa.issubmitted=0
WHERE sa.studentid=568;
答案 0 :(得分:1)
MySQL has that limitation;你无法更新你选择的表格而且你什么都不做。
目前,您无法更新表并从子查询中的同一表中进行选择。
但是你可以这样做:
CREATE TEMPORARY TABLE studentassessmentids (
`id` INT,
PRIMARY KEY (`id`)
);
LOCK TABLE studentassessment WRITE;
INSERT INTO studentassessmentids (SELECT ... prepare your ids);
UPDATE studentassessment sa
SET sa.issubmitted=FALSE
WHERE sa.studentassessmentid NOT IN (
SELECT id
FROM studentassessmentids AS ids
WHERE ids.id = sa.studentassessmentid
)
UNLOCK TABLES;
DROP TEMPORARY TABLE studentassessmentids;
我从我的头顶编写代码,所以它不能直接使用,但希望你能够采用这个想法。
如果您可以将查询重写为JOIN
语句组,例如(来自mysql.com):
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;
它应该可以工作,但我不知道如何在不编写难以理解的代码的情况下使用连接实现NOT IN
。
答案 1 :(得分:0)
找到答案
UPDATE studentassessment dest,
(
SELECT studentassessmentid,assessmentperiodid
FROM studentassessment sa WHERE sa.studentid=568
AND sa.studentassessmentid<>
(
SELECT studentassessmentid FROM studentassessment s
WHERE s.studentid=568
AND sa.assessmentperiodid=s.assessmentperiodid
ORDER BY studentassessmentid DESC LIMIT 1
)
)src
SET dest.issubmitted=FALSE
WHERE dest.studentassessmentid=src.studentassessmentid