内部连接没有重复记录

时间:2011-09-14 23:56:34

标签: php mysql inner-join

我有两张桌子(问题表和答案表)。

问题表

id question
1  what is your name?
2  how old are you?

答案表

id  answer  questionid
1   john     1
2   smith    1
3   waiyan   1
4   20       2
5   21       2
6   22       2

当我选择记录时,结果如下。

SELECT * FROM question INNER JOIN answer on questionid= question.id

what is your name?
john
what is your name?
smith
what is your name?
waiyan
how old are you?
20
how old are you?
21
how old are you?
22

我想删除重复的问题陈述。 我想得到关注。

What is your name?
John
smith
waiyan  

how old are you?  
20 
21    
22

请有人帮我怎么写。 我是mysql的初学者。 很抱歉我的英语用法不好。

1 个答案:

答案 0 :(得分:2)

问题在于你的PHP代码,而不是你的MySQL语句。您只需在与上一个问题不同的情况下打印问题。有很多方法可以做到这一点。请记住,在SQL查询中,您需要执行以下操作:

SELECT * FROM question INNER JOIN answer 
    on questionid= question.id 
    order by question.id

确保不会重复相同问题的答案。然后执行以下操作(感谢@drrcknlsn修复我对php的尝试):

$last_question = "";
foreach ($results as $row) {
    if ($last_question !== $row["question.question"]) {
        echo $row["question.question"];
    }
    echo $row["answer.answer"];
    $last_question = $row["question.question"];
}