开发者

MySQL Joining three tables

开发者 https://www.devze.com 2023-01-01 02:20 出处:网络
I am doing a query with three tables, the problem was one table has many occurrences of id of another.

I am doing a query with three tables, the problem was one table has many occurrences of id of another.

sample data:

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

How can I get all user information and all answer and its description, I used GROUP by user.id but it only returns only one answer.

I want to return something like this list all of users answer:

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

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


You'd need to use a pivot table

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

That's my best guess at what you want to do from the schema you provided (I doubt it's complete, which is why I guessed at the question_id part. I used LEFT JOIN so that if the user doesn't have an answer for that question, it won't hurt anything. Also, GROUP_CONCAT will automatically combine the field if multiple answers exist. So if there are 2 rows from Q1 for that particular user, it'll combine the two into "ans1, ans2"...

0

精彩评论

暂无评论...
验证码 换一张
取 消