在mySql中并排合并两个表中的数据

时间:2018-10-11 06:44:21

标签: mysql

我正在使用mysql。我有两个表issue_statusesworkflows,如下所示

issue_statuses=>

    +----+---------------+
    | id |      name     |
    +----+---------------+
    |  1 | New           |
    |  2 | AssignedToFix |
    |  3 | ForReview     |
    |  4 | Resolved      |
    |  5 | Closed        |
    |  6 | Pending       |
    +----+---------------+

workflows=>

    +-----+------------+---------------+---------------+---------+
    | id  | tracker_id | old_status_id | new_status_id | role_id |
    +-----+------------+---------------+---------------+---------+
    | 130 |          1 |             1 |             5 |       5 |
    | 131 |          1 |             2 |             5 |       5 |
    | 132 |          1 |             3 |             4 |       5 |
    | 133 |          1 |             3 |             5 |       5 |
    | 134 |          1 |             4 |             5 |       5 |
    +-----+------------+---------------+---------------+---------+

我需要什么? 我需要合并下面两个表中的数据

+----+---------------+---------------+---------+
| id |     name      | new_status_id | role_id |
+----+---------------+---------------+---------+
|  1 | New           | 5             | 5       |
|  2 | AssignedToFix | 5             | 5       |
|  3 | ForReview     | 5,4           | 5       |
|  4 | Resolved      | 5             | 5       |
|  5 | Closed        | null          | null    |
|  6 | Pending       | null          | null    |
+----+---------------+---------------+---------+

我需要issue_statuses表中的所有记录和workflows表中的匹配记录。并且如果new_status_id有多个值,我需要将这些值组合为逗号分隔。


到目前为止我做了什么? 我写了以下查询。

SELECT 
    i.id, 
    i.name, 
    (select GROUP_CONCAT(distinct(new_status_id)) from bitnami_redmine.workflows where old_status_id= i.id and role_id = 5 and tracker_id=1) as new_status_id,
    w.role_id
FROM
    bitnami_redmine.issue_statuses i
JOIN
    bitnami_redmine.workflows w
ON
    w.old_status_id = i.id
WHERE 
    w.role_id = 5 and w.tracker_id=1;

但是我没有从issue_statuses中获得所有记录,而且记录还在重复。因此,我放置了distinct,并消除了重复的组。结果如下所示, enter image description here enter image description here

如何显示issue_statuses中的所有记录?任何帮助都深表感谢。...

1 个答案:

答案 0 :(得分:1)

使用左连接并在wluroase中添加w.role_id = 5和w.tracker_id = 1

SELECT 
    i.id, 
    i.name, 
    (select GROUP_CONCAT(distinct(new_status_id)) from bitnami_redmine.workflows where old_status_id= i.id and role_id = 5 and tracker_id=1) as new_status_id,
    w.role_id
FROM bitnami_redmine.issue_statuses i
left JOIN bitnami_redmine.workflows w
ON w.old_status_id = i.id
and w.role_id = 5 and w.tracker_id=1;