如何从同一SQL中的两个不同表中获取两个值

时间:2016-12-09 12:39:01

标签: php mysql sql

我有两张桌子

  • 问题

    • Id_question
    • 问题
  • 答案

    • Id_question
    • Id_answers
    • 答案

如果我使用此查询,

select q.question, a.answer from Question q, Answers a where q.Id_question= a.Id_question

我得到的问题和相关的答案,但我重复问题,例如

问题

First question?
  Yes
First question?
 No
Second question?
Probably
Second question?
 Yei

获得第一个问题并提出相关答案然后得到第二个问题和相关答案而不重复问题是不可能的?

1 个答案:

答案 0 :(得分:4)

It's not quite clear what you are looking for in the output, but you could try something like this:

select q.question, group_concat(a.answer)
from Question q, Answers a 
where q.Id_question= a.Id_question
group by q.question

the group_concat function will give you a comma-separated list. The output should look like:

First question?  | Yes, No
Second question? | Probably, Yei