MySQL:子查询返回多行

时间:2013-05-14 11:46:43

标签: mysql subquery

我需要在更新问题表后从响应表中删除行但是我收到此错误:子查询返回多行。有没有办法让它发挥作用?

CREATE TRIGGER delete_responses AFTER UPDATE ON  questions
FOR EACH ROW 
BEGIN 
IF NEW.active != OLD.active 
THEN DELETE FROM responses WHERE option_id = (
SELECT option_id
FROM options
WHERE question_id = OLD.question_id);

4 个答案:

答案 0 :(得分:1)

是的,请改用JOIN

DELETE r
FROM responses AS r
INNER JOIN options AS o ON r.option_id = o.option_id
WHERE o.question_id = OLD.question_id;

答案 1 :(得分:0)

=更改为= ANYin

CREATE TRIGGER delete_responses AFTER UPDATE ON  questions
FOR EACH ROW 
BEGIN 
IF NEW.active != OLD.active 
THEN DELETE FROM responses WHERE option_id in (
SELECT option_id
FROM options
WHERE question_id = OLD.question_id);

答案 2 :(得分:0)

使用“in”:

CREATE TRIGGER delete_responses AFTER UPDATE ON  questions
FOR EACH ROW 
BEGIN 
IF NEW.active != OLD.active 
THEN DELETE FROM responses WHERE option_id in (
SELECT option_id
FROM options
WHERE question_id = OLD.question_id);

或限制子查询,使其只返回一行。

答案 3 :(得分:0)

您可以通过限制或不同将子查询的结果限制为1,或者如果您要删除子查询中的所有已创建结果,则需要使用WHERE id IN (....)