MySQL - 在2个表上转移一对多的关系

时间:2017-05-03 19:51:45

标签: mysql pivot

我需要透视表,它可以为视图完成,也可以将数据转储到已经设置为透视表的预先存在的表中。我的主要问题是知道如何选择和转动数据。

示例数据

表1:

user_id       user_email       first_name       last_name
-------------------------------------------------------------
1             jdoe@huh.com     John             Doe
2             jcarter@aol.com  Jimmy            Carter

表2:

user_id       type       job_title       job_description
---------------------------------------------------------
1             Job 1      Some Job        play all day!
1             Job 2      Another Job     all work no play!
2             Job 1      Clown           IT's not funny

PIVOTED TABLE
我想要实现的是:
为了便于使用,我缩短了表名和数据。

uid    email    fname    lname    jtitle-1    jdesc-1    jtitle-2    jdesc-2
----------------------------------------------------------------------------
1      jdoe@>  John     Doe      Some Job    play all>   Another J>  all wo>
2      jcar@>  Jimmy    Carter   Clown       IT's not>   null        null

我四处寻找一些例子,但没有一个正是我正在寻找的。

MySQL pivot table
http://stratosprovatopoulos.com/web-development/mysql/pivot-a-table-in-mysql/


更新
当然,在发布之后不久,我就遇到了一个解决方案 http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/

这就是诀窍
MAX(IF(pa.fieldname ='size',pa.fieldvalue,NULL))AS大小

1 个答案:

答案 0 :(得分:0)

你正在寻找的是一个 Joe Celko (SQL for Smarties)风格的支点,通过对主表PK进行分组并根据相对“类型”选择性地选择table-2值

SELECT u.user_id AS uid,
    u.user_email AS email,
    u.first_name AS fname,
    u.last_name AS lname,
    MAX(CASE WHEN j.type = 'Job 1' THEN j.job_title ELSE NULL END) AS `jtitle-1`,
    MAX(CASE WHEN j.type = 'Job 1' THEN j.job_description ELSE NULL END) AS `jdesc-1`,
    MAX(CASE WHEN j.type = 'Job 2' THEN j.job_title ELSE NULL END) AS `jtitle-2`,
    MAX(CASE WHEN j.type = 'Job 2' THEN j.job_description ELSE NULL END) AS `jdesc-2`,
    MAX(CASE WHEN j.type = 'Job 3' THEN j.job_title ELSE NULL END) AS `jtitle-3`,
    MAX(CASE WHEN j.type = 'Job 3' THEN j.job_description ELSE NULL END) AS `jdesc-3`,
    MAX(CASE WHEN j.type = 'Job 4' THEN j.job_title ELSE NULL END) AS `jtitle-4`,
    MAX(CASE WHEN j.type = 'Job 4' THEN j.job_description ELSE NULL END) AS `jdesc-4`,
    MAX(CASE WHEN j.type = 'Job 5' THEN j.job_title ELSE NULL END) AS `jtitle-5`,
    MAX(CASE WHEN j.type = 'Job 5' THEN j.job_description ELSE NULL END) AS `jdesc-5`
FROM users AS u
LEFT JOIN jobs AS j ON j.user_id = u.user_id
GROUP BY u.user_id;