MySQL错误:子查询返回超过1行。如何优化此查询?

时间:2016-04-10 15:48:12

标签: mysql

SET @v1 := (SELECT questor.questioncart.idQuestionCart FROM questioncart WHERE User_username = "eamin" ORDER BY idQuestionCart DESC LIMIT 1);
SET @v2 := (SELECT questor.questioncart_has_question.Question_idQuestion FROM questioncart_has_question WHERE QuestionCart_idQuestionCart = @v1);
SELECT questor.question.questionText FROM question WHERE idQuestion = @v2;

在这个MySQL查询中,我得到“Subquery返回超过1行”错误。 MySQL将第二个查询(@ v2)指向为创建错误的错误。我能做些什么来解决这个问题?你可以为我提供任何优化的mysql来解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您应该将查询作为单个查询运行。让MySQL为您做优化。至少,这节省了返回数据库进行多次查询的时间:

SELECT q.questionText
FROM question q
WHERE idQuestion IN (SELECT qchq.Question_idQuestion
                     FROM questioncart_has_question qchq JOIN
                          (SELECT qc.idQuestionCart
                           FROM questioncart qc
                           WHERE User_username = 'eamin'
                           ORDER BY idQuestionCart DESC
                           LIMIT 1
                          ) qc
                          ON qchq.QuestionCart_idQuestionCart = qc.idQuestionCart
                     );