MySQL加入三个表

时间:2010-05-21 12:17:23

标签: php mysql

我正在用三个表进行查询,问题是一个表有多次出现另一个id。

示例数据:

users: id

answers: 
id:1
user_answer :1
id:1
user_answer :2
id:1
user_answer :3

Questions: 
id:1
answers :answer description
id:2
answers :answer description
id:3
answers :answer description

如何获取所有用户信息及所有答案及其描述,我使用GROUP by user.id但它只返回一个答案。

我希望返回所有用户回答的列表:

Name         Q1          Q2    
USERNAME    ans1,ans2    ans1,ans2             comma separated description of answer here

alt text http://christianruado.comuf.com/images/schema.png

1 个答案:

答案 0 :(得分:1)

您需要使用数据透视表

SELECT users.id, users.name, 
    GROUP_CONCAT(q1.answer SEPARATOR ', ') AS `Q1`, 
    GROUP_CONCAT(q2.answer SEPARATOR ', ') AS `Q2`, 
    GROUP_CONCAT(q3.answer SEPARATOR ', ') AS `Q3`
FROM `users` AS users,
    LEFT JOIN `answers` AS a1 ON a1.id = users.id
    LEFT JOIN `questions` AS q1 ON q2.id = a1.user_answer
    LEFT JOIN `answers` AS a2 ON a2.id = users.id
    LEFT JOIN `questions` AS q2 ON q2.id = a2.user_answer
    LEFT JOIN `answers` AS a3 ON a3.id = users.id
    LEFT JOIN `questions` AS q3 ON q3.id = a3.user_answer
WHERE q1.question_id = 1
    AND q2.question_id = 2
    AND q3.question_id = 3
GROUP BY users.id

这是我对你想要从你提供的模式做什么的最好的猜测(我怀疑它是完整的,这就是为什么我猜到了question_id部分。我使用LEFT JOIN以便如果用户没有答案这个问题,它不会伤害任何东西。另外,如果存在多个答案,GROUP_CONCAT将自动组合该字段。因此,如果该特定用户的Q1有2行,它将两者合并为“ans1,ans2”。