mysql - 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
解决方案
使用 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
推荐阅读
- azure - 计时器触发器 Azure 功能停止工作,没有任何更改
- java - 无法从 EditText 获取文本
- c# - 如何使用 WebRequest C# 在没有 ssl 验证的情况下发送请求?
- python - 我如何在其他功能中使用 get_queryset()object 'list_object'
- sql - 检测包含除“,”和“\ n”以外的特殊字符的列 - Postgresql
- java - Docker 在 IntelliJ 项目设置中找不到我的 .java 文件
- scala - 如何在 Gatling 资源方法中的请求之间传递值?
- amazon-web-services - 在 AWS Secret Manager 和 Active Directory 之间同步密码
- python - 如何使用 `np.choose` 或 `np.take` 或类似方法在 numpy 中对它进行矢量化?
- sql - 检索新值时触发器在 PLSQL 中不起作用