使用存储过程从表中获取数据

时间:2016-04-21 09:08:26

标签: mysql sql stored-procedures while-loop

我有一张名为的表 CUSTOMERANSWER表 - (customeranswerID(pk),customerID(fk),surveyID(fk),question(fk),Answer,answersdate)

我试图通过特定的surveyID获取数据,其中questionid应该等于no。问题表中的问题。

CREATE DEFINER=`root`@`localhost` PROCEDURE `prc_feedbackAnswers`(IN `inputsurveyID` INT(11))
BEGIN
DECLARE _questionID INT;
DECLARE _questioncount INT;
SET _questionID = 1;
SET _questioncount = (SELECT count(questionID) From QUESTIONOPTION Where surveyID = inputsurveyID);
WHILE (_questionID <=(_questioncount+1))
DO
SELECT surveyID, questionID, answer
FROM CUSTOMERANSWER
WHERE surveyID = inputsurveyID AND questionID = _questionID;
SET _questionID = _questionID + 1;
END WHILE;
END

我得到的输出是

enter image description here

我想要的是在一张桌子里。这里给出了surveyID,questionId,每次回答。

请帮忙。

2 个答案:

答案 0 :(得分:0)

而不是:

ValidationError({'age': [u'This field is required.'], 'name': [u'This field is required.']}) is not JSON serializable

试试这个:

WHILE (_questionID <=(_questioncount+1))
DO
    SELECT surveyID, questionID, answer
    FROM CUSTOMERANSWER
    WHERE surveyID = inputsurveyID AND questionID = _questionID;
    SET _questionID = _questionID + 1;
END WHILE;

答案 1 :(得分:0)

我不确定我是否理解这个问题,但你可能会想要这些内容

SELECT surveyID, questionID, answer
FROM CUSTOMERANSWER
join  (
    SELECT inputsurveyID, count(questionID) as Q
    From QUESTIONOPTION 
    Where surveyID = inputsurveyID -- (not required, might be more efficient)
    group by inputsurveyID
) as N
on surveyID = inputsurveyID 
and questionID = Q