如何在不使用mysql的完全外连接的情况下实现这一点?

时间:2016-02-23 12:35:52

标签: mysql sql database

我有这张表:

1)customfields

+------+---------+-------+
|userid| fieldid | value |
+------+---------+-------+
|  1   |   1     |  5c54 |
|  2   |   1     |  cerc |
|  2   |   3     |  3545 |

2)users

+------+---------+
|userid| name    |
+------+---------+
|  1   |   ale   |
|  2   |   ben   |
|  3   |   jak   |

我想实现:

表格piva

中的

fieldidcustomfields = 1 表code

中的

fieldidcustomfields = 3

+--------+---------+-------+
|name    | piva    | code  |
+--------+---------+-------+
|  ale   |   5c54  |       |
|  ben   |   cerc  |  3545 |

我不知道如何实现这个

3 个答案:

答案 0 :(得分:2)

您可以使用条件聚合

SELECT c.userid, u.name, 
       MAX(CASE WHEN fieldid = 1 THEN value END) AS piva,
       MAX(CASE WHEN fieldid = 3 THEN value END) AS code
FROM customfields AS c
INNER JOIN users AS u ON c.userid = u.userid
GROUP BY c.userid, u.name

答案 1 :(得分:0)

这与full outer join(MySQL不支持)无关。一种方法只是条件聚合的连接:

select u.name,
       max(case when cf.fieldid = 1 then value end) as piva,
       max(case when cf.fieldid = 3 then value end) as code
from customfields cf join
     users u
     using (userid)
group by u.name;

答案 2 :(得分:0)

您可以尝试此SQL查询:

Select u.name,
(Select value from customfields where fieldid = 1 and userid= u.userid) as piva, 
(Select value from customfields where fieldid =3 and userid = u.userid) as code 
from users u