有很多mysql查询

时间:2017-03-06 05:31:51

标签: mysql sql relationship has-many

我有一个带有用户表和答案表的数据库。每个用户有30个答案。我想将用户及其所有答案导出到一行。

e.g:

ID  | email   | answer_1 | answer_2 | answer_3 | etc...
----|---------|----------|----------|----------|--------
1   | e@g.com |  foo     | bar      | baz      | ....  

我目前有

SELECT *
    FROM users
    LEFT JOIN answers AS A 
        ON users.id = A.user_id
    WHERE email IS NOT NULL

这为每个用户创建了30行,并针对每个用户给出了答案。如何将每个用户分成一行,每个答案都有一列?

1 个答案:

答案 0 :(得分:2)

您可以尝试使用数据透视查询,如下所示:

SELECT uid, email,
       MAX(CASE WHEN a.aid = 1 THEN a.answer END) AS answer_1,
       MAX(CASE WHEN a.aid = 2 THEN a.answer END) AS answer_2,
       MAX(CASE WHEN a.aid = 3 THEN a.answer END) AS answer_3
       -- add more CASE expressions to cover all 30 answers
FROM users u
LEFT JOIN answers a
    ON u.id = a.user_id
WHERE u.email IS NOT NULL
GROUP BY u.id, u.email

假设:answers表有一个id列,用于识别30个答案中的每一个并对其进行编号。没有这个,查询可能是一个真正的痛苦。我还假设每个用户将有30个答案。缺少答案会在不存在的情况下显示为NULL