select query issue

Discussion in 'Databases' started by dizyn, Apr 20, 2008.

  1. #1
    Hi

    I have two tables

    questions
    answers

    One question can have many answers

    i want to select all the questions with all answers

    i also want to select the questions which are not answered yet.

    thank you
     
    dizyn, Apr 20, 2008 IP
  2. Student Gamers

    Student Gamers Banned

    Messages:
    47
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Bit confused by what you want, do you want a query that will list all the questions with all the answers to each under them? So..

    Question 1
    Answer 1
    Answer 2

    Question 2

    etc...

    And for the second you want a list of questions that have no answers attatched? Do you have the tables pre made? If so what are cell headings to them?
     
    Student Gamers, Apr 20, 2008 IP
  3. dizyn

    dizyn Active Member

    Messages:
    251
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    yes
    i want query that show all questions and answers to them

    question table
    qid, quest

    answer table
    aid, answer, qid
     
    dizyn, Apr 20, 2008 IP
  4. Student Gamers

    Student Gamers Banned

    Messages:
    47
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Sorry I didn't reply quicker.. This will display the questions with all their answers:

    <?php
    $getQuestions = mysql_query("SELECT * FROM `questions`");
    while($question = mysql_fetch_assoc($getQuestions))
    {
        $getAnswers = mysql_query("SELECT * FROM `answers` WHERE `qid` = '".$question['qid']."'");
    
        echo '<b>'.$question['quest'].'</b><br />';
        echo '<ul>';
    
        while($answer = mysql_fetch_assoc($getAnswers))
        {
            echo '<li>'.$answer["answer"].'</li>';
        }
    
        echo '</ul>';
    }
    
    ?>
    PHP:
    And this will show questions that still need answering:

    <?php
    $getQuestions = mysql_query("SELECT `qid` FROM `questions`");
    while($question = mysql_fetch_assoc($getQuestions))
    {
        $getAnswers = mysql_query("SELECT * FROM `answers` WHERE `qid` = '".$question['qid']."'");
        
        if(mysql_num_rows($getAnswers) == "0")
        {
            echo $question['quest'].'<br />';
    
        }
    }
    
    ?>
    PHP:
     
    Student Gamers, Apr 20, 2008 IP
  5. dizyn

    dizyn Active Member

    Messages:
    251
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #5
    this is the simplest way and not a good one.

    Here is the query that will do the work.

    SELECT u.login, q.PK_ID, q.question, answers.answer
    FROM questions q
    LEFT JOIN answers ON q.PK_ID = answers.FK_QUESTION_ID
    INNER JOIN user u ON ( u.PK_ID = q.FK_USER_ID ) 
    Code (markup):
     
    dizyn, Apr 21, 2008 IP