没有重复记录的内连接

发布于 2024-12-04 12:44:34 字数 725 浏览 1 评论 0原文

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

问题表

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的初学者。 很抱歉我的英语用法不好。

I have two table (question table and answer table).

Question Table

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

Answer Table

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

When I selected records,The results is following.

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

I want to remove duplicate question statement.
I want to get following.

What is your name?
John
smith
waiyan  

how old are you?  
20 
21    
22

Please Someone help me how to write it.
I am really beginner for mysql.
So sorry for my bad english usage.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

段念尘 2024-12-11 12:44:34

问题出在你的 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"];
}

The issue is in your php code, not your MySQL statements. You need to only print the question when it's different from the previous question. There are lots of ways to do this. Keep in mind that in your SQL query, you'll need to do:

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

To be sure that answers for the same question are not repeated. Then do something like the following (thanks to @drrcknlsn for fixing my attempt at 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"];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文