dtg7662 2009-04-01 11:39
浏览 20
已采纳

如何对表示具有多个答案的民意调查的两个表使用一个查询?

I have two tables poll and poll_answers, which represent a poll and the options to choose from to answer a question from the poll. EX:

Am I poor at SQL?

  • yes
  • yes, you do
  • change craft

and the co-responding tables:

poll

pollID pollQuestion

 1 | Am I poor at SQL?

poll_answers

pollAnswerID pollAnswerText pollID

  1 | yes | 1

  2 | yes, you do | 1

  3 | change craft | 1

and this is how I get the data:

$polls=$db->get_results("SELECT pollID, pollQuestion FROM poll",ARRAY_A);
    foreach ($polls as $poll_field)
    {
        $poll['id']=$poll_field['pollID'];
        $poll['question']=$poll_field['pollQuestion'];
        $tmp=$poll['id'];
        //answers
        $answers=$db->get_results("SELECT pollAnswerID, pollAnswerText FROM poll_answers WHERE pollID='$tmp'",ARRAY_A);
            {
            //and so on , I think you get the idea.
            }


    }

It looks very clumsy to me as I think that it is possible to get the data with only one SQL query using INNER JOIN on the ID match...I just couldn't do it. Can you help? Keep in mind that there are multiple polls in my database.


Edit: thank you for the answers so far. I appreciate the help. But I didn't explain the question well. Is it possible to get all the polls with all the answers in an array or object using only one SELECT. In the answers so far you used the $tmp variable which is already taken from a previous query. So is it possible to do it or is it me not getting the answers?

  • 写回答

3条回答 默认 最新

  • dssj88098 2009-04-01 11:44
    关注
    SELECT pollQuestion, pollAnswerID, pollAnswerText
    FROM   poll_answers pa, poll p
    WHERE  p.pollID='$tmp'
           AND pa.pollId = p.pollID
    

    or, if you prefer INNER JOIN syntax,

    SELECT pollQuestion, pollAnswerID, pollAnswerText
    FROM   poll p
    INNER JOIN
           poll_answers pa
    ON     pa.pollId = p.pollID
    WHERE  p.pollID='$tmp'
    

    To get eveything in an array, you use:

    SELECT  -1, pollQuestion
    FROM    poll p
    WHERE   p.pollID = @pollID
    UNION ALL
    SELECT  pollAnswerID, pollAnswerText
    FROM    poll_answers pa
    WHERE   pa.pollID= @pollID
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看