我希望这是有道理的,让我详细说明:
有一个测验程序跟踪数据表,其中每一行都有...
QuestionID和AnswerID(每个都有一个表).因此,由于一个错误,有一堆QuestionID设置为NULL,但相关AnswerID的QuestionID在Answers表中.
所以说QuestionID是NULL,AnswerID是500,如果我们转到Answers表并找到AnswerID 500,那么有一个带有QuestionID的列应该是NULL值所在的列.
所以基本上我想将每个NULL QuestionID设置为等于在跟踪表中的AnswerID的Answer行上的Answers表中找到的QuestionID(与正在写入的NULL QuestionID相同的行).
我该怎么做?
UPDATE QuestionTrackings SET QuestionID = (need some select query that will get the QuestionID from the AnswerID in this row) WHERE QuestionID is NULL AND ... ?
不知道我怎么能够从匹配的AnswerID中将QuestionID分配给QuestionID ...
update q set q.QuestionID = a.QuestionID from QuestionTrackings q inner join QuestionAnswers a on q.AnswerID = a.AnswerID where q.QuestionID is null -- and other conditions you might want
我建议在运行更新之前检查要更新的结果集(相同的查询,只需选择):
select * from QuestionTrackings q inner join QuestionAnswers a on q.AnswerID = a.AnswerID where q.QuestionID is null -- and other conditions you might want
特别是每个答案id是否肯定只有1个相关的问题ID.
如果没有update-and-join表示法(并非所有DBMS支持),请使用:
UPDATE QuestionTrackings SET QuestionID = (SELECT QuestionID FROM AnswerTrackings WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID) WHERE QuestionID IS NULL AND EXISTS(SELECT QuestionID FROM AnswerTrackings WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)
通常在这样的查询中,您需要使用包含子查询的EXISTS子句限定WHERE子句.这可以防止UPDATE践踏没有匹配的行(通常使所有值都为空).在这种情况下,由于缺少的问题ID会将NULL更改为NULL,因此可以说无关紧要.
我不知道你是否在MySQL Workbench上遇到了与我相同的问题,但是INNER JOIN
在FROM
声明之后运行查询对我来说不起作用.我无法运行查询,因为该程序抱怨该FROM
语句.
因此,为了使查询工作,我将其更改为
UPDATE table1 INNER JOIN table2 on table1.column1 = table2.column1 SET table1.column2 = table2.column4 WHERE table1.column3 = 'randomCondition';
代替
UPDATE a FROM table1 a INNER JOIN table2 b on a.column1 = b.column1 SET a.column2 = b.column4 WHERE a.column3 = 'randomCondition';
我想我的解决方案是MySQL的正确语法.
UPDATE "QuestionTrackings" SET "QuestionID" = (SELECT "QuestionID" FROM "Answers" WHERE "AnswerID"="QuestionTrackings"."AnswerID") WHERE "QuestionID" is NULL AND ...
我有同样的问题.这是一个类似于eglasius的工作解决方案.我正在使用postgresql.
UPDATE QuestionTrackings SET QuestionID = a.QuestionID FROM QuestionTrackings q, QuestionAnswers a WHERE q.QuestionID IS NULL
它抱怨如果在第1行使用q代替表名,并且在第2行的QuestionID之前不应该有任何内容.