我有一张表有以下结构:
| pid | email | email_type |
| 1 | x | 1 |
| 1 | y | 2 |
| 1 | z | 3 |
| 2 | ab | 1 |
| 3 | cd | 2 |
现在,我希望我的结果仅为pid
格式的email_type[1 & 2]
参数:
案例pid=1
| pid | email_p | email_w |
| 1 | x | y |
案例pid=2
| 2 | ab | NULL |
案例pid=3
| 3 | NULL | cd |
此处email_p
代表email_type=1
& email_w
代表email_type=2
我正在使用以下查询,除了案例pid=2
外,其工作正常。案例I&案例III已成功获取。请提供一些解决方案(如果可能的话)。
SELECT `e`.`pid`, `e`.`email` AS `email_p`, `e1`.`email` AS `email_w` FROM `table1` AS `e` LEFT JOIN `table1` AS `e1` ON e.pid=e1.pid AND e1.email_type=2 WHERE (e.pid IN (1) AND e.email_type=1)
e.pid = 2
时失败并返回空结果集&请提供解决方案e.pid IN (1,2,3)
适用于所需格式。#MYSQL
答案 0 :(得分:3)
试试这个
SELECT pid,
MAX(CASE WHEN email_type=1 THEN email END ) as email_p ,
MAX(CASE WHEN email_type=2 THEN email END ) as email_w
FROM tableName
WHERE email_type IN (1,2)
GROUP BY pid