mysql查询加入query2

时间:2014-12-29 08:06:52

标签: mysql database mysqli

我有以下MYSQL查询:

SELECT * 
FROM quizquestions 
INNER JOIN option2 ON quizquestions.question_id=option2.question_id 
WHERE quizquestions.quiz_id=13

基本上,我有两个表,一个表有问题,另一个表存储4个选项。例如,quizquestions表将如下:

Question_id (Primary Key), quiz_id(to link it to the quiz), question

  61                       13                               1+2

然后选项表如下:

Option id (Primary Key), Question_id(To link it to the correct question), optionvalue

      181                61                                               3

目前,我使用循环来显示问题和选项,但是,每当我使用上面显示的INNER JOIN查询时,我得到以下内容:

question_id    quiz_id    question    optionid    question_id    optionvalue

     61            13       1+2        181         61           1
     61            13       1+2        182         61           2
     61            13       1+2        183         61           3
     61            13       1+2        184         61           4

但是,我希望它显示如下:

Question_id    Quiz_ID     question   optionvalue    optionvalue    optionvalue    optionvalue

    61          13          1+2       1               2            3               4

这样我就不会像第一栏中看到的那样重复问题_id / quiz_id。

这可以实现吗?

1 个答案:

答案 0 :(得分:2)

SELECT q.Question_id as questionId, q.Quiz_ID as quizId, q.question as question, GROUP_CONCAT(op.optionvalue SEPARATOR ' ') as options
FROM quizquestions q INNER JOIN option2 op ON q.question_id=op.question_id WHERE q.quiz_id=13
GROUP BY q.Question_id

OR

    SELECT q.Question_id as questionId, q.Quiz_ID as quizId, q.question as question, 
SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(op.optionvalue), ',', 1), ',', -1) AS option1,
SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(op.optionvalue), ',', 2), ',', -1) AS option2,
SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(op.optionvalue), ',', 3), ',', -1) AS option3,
SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(op.optionvalue), ',', 4), ',', -1) AS option4
    FROM quizquestions q INNER JOIN option2 op ON q.question_id=op.question_id WHERE q.quiz_id=13
    GROUP BY q.Question_id

试试这个。