首页 > 解决方案 > How to get data from 2 parent tables that are linked via a intermediary table

问题描述

I have the following tables like below:

Table - mytags

| tag_id | tag_name |
|    1   |   home   |
|    2   |   work   |

TABLE - mytasks

| task_id |     task_name     |
|    14   | do my the dishes  |
|    12   | Make presentation |

TABLE - mytasks_mytags

| mytag_id | mytask_id |
|     1    |    14     |
|     2    |    14     |

What i would like to get is the task_id , task_name and lastly mytags.tag_name the task_id is associated with , i beleive i will need a query that runs through all 3 tables , but i am not quite sure how to go about building this mysql query, can someone please assist me.

So what i would like is something like:

| task_id |     task_name     | tag_name
|    14   | do my the dishes  |   home , work
|    12   | Make presentation |    null

标签: mysqlnode.js

解决方案


使用 mysql,您可以通过 task_id 使用内部连接和 group_concat 组

    select  a.task_id, a.task_name, group_concat(b.tag_name ) tag_name
    from mytasks_mytags c 
    inner join mytasks a on c.mytask_id = a. task_id
    left  join mytags b on b.tag_id = c.mytag_id 
    group by  a.task_id, a.task_name

推荐阅读