我对 mySQL 查询还很陌生,并且努力获得我需要的结果。 我有两个需要显示的用户信息表。表格如下:
users
+----+------------------+
| id | email |
+----+------------------+
| 1 | joe@hotmail.com |
| 2 | john@hotmail.com |
| 3 | fred@hatmail.com |
+----+------------------+
user_detail
+----------+--------+--------+
| detailid | userid | detail |
+----------+--------+--------+
| 1 | 1 | Joe |
| 2 | 1 | Soap |
| 1 | 2 | John |
| 2 | 2 | Doe |
| 1 | 3 | Fred |
| 2 | 3 | Bloggs |
+----------+--------+--------+
我构建了以下连接表的查询:
SELECT id, detail , email
FROM users
LEFT JOIN user_detail
ON users.id=user_detail.userid
ORDER by id
查询产生这个结果:
+--------+--------+------------------+
| userid | detail | email |
+--------+--------+------------------+
| 1 | Joe | joe@hotmail.com |
| 1 | Soap | joe@hotmail.com |
| 2 | John | john@hotmail.com |
| 2 | Doe | john@hotmail.com |
| 3 | Fred | fred@hatmail.com |
| 3 | Bloggs | fred@hatmail.com |
+--------+--------+------------------+
我正在努力实现的是:
+--------+---------+---------+------------------+
| userid | detail1 | detail2 | email |
+--------+---------+---------+------------------+
| 1 | Joe | Soap | joe@hotmail.com |
| 2 | John | Doe | john@hotmail.com |
| 3 | Fred | Bloggs | fred@hatmail.com |
+--------+---------+---------+------------------+
你能帮我指出正确的方向吗?
最佳答案
SELECT id,
MAX(CASE WHEN detaildid=1 THEN detail END) as detail1,
MAX(CASE WHEN detaildid=2 THEN detail END) as detail2,
email
FROM users
LEFT JOIN user_detail
ON users.id=user_detail.userid
GROUP BY id,email
ORDER by id
如果你有很多 detailids,这可以动态编写。
关于mySQL 表连接 - 错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201306/