我对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 |
+--------+---------+---------+------------------+
你能帮忙并指出我正确的方向吗?
答案 0 :(得分:2)
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
如果您有许多详细信息,可以动态编写。
答案 1 :(得分:2)
您可以两次加入同一个表,一次用于详细信息ID 1,另一个用于详细信息ID 2
SELECT id, d1.detail, d2.detail, email
FROM users u
LEFT JOIN user_detail d1
ON u.id = d1.userid
AND d1.detailid = 1
LEFT JOIN user_detail d2
ON u.id = d2.userid
AND d2.detailid = 2
ORDER BY ID