mysql - Mysql查询使用多对多关系连接两个表
问题描述
我有三个称为Notes
另一个表的表Tags
,第三个称为联接表NoteTagsJoin
,联接表包含两个外键主 Note id 和 Primary Tag id。我使用这个查询来获取所有带有 tagId 的笔记:
SELECT * FROM notes INNER JOIN note_tag_join ON notes.entryId = note_tag_join.noteId WHERE note_tag_join.tagId =:tagId
这个查询获取所有标签:
SELECT * FROM tags INNER JOIN note_tag_join ON tags.tagId = note_tag_join.tagId WHERE note_tag_join.noteId =:noteId
如何通过一个查询仅使用 Note id 获取 Note 及其所有标签?
解决方案
SELECT * FROM table_name
LEFT JOIN table_name2 ON table_name.id = table_name2.id
LEFT JOIN table_name3 ON table_name2.id = table_name3.id
WHERE table_name.id = id;
用您正在使用的适当的 id 更改“id”。重要的是 JOIN 中的 id 是连贯的,否则它们之间将没有链接。
推荐阅读
- swift - UnsafeMutableRawPointer copyMemory(from:byteCount:) 是同步操作吗?
- r - 根据 r 中其他两个变量之间的数值差异创建一个新变量
- javascript - 将按钮添加到愿望清单
- r - R通过附加列组合重复行
- sql - SQL Server INSERT-OUTPUT 包括来自其他表的列
- amazon-web-services - AWS Lambda 未将文件从 /var/task 复制到 /tmp 文件夹
- python-3.x - 在 Airflow 中获取操作员的执行日期
- c++ - C ++ WinApi - 从父窗口向所有子窗口发送点击,在同一位置
- c++ - 为什么/何时自动刷新 cout 缓冲区?
- python - 如何在客户端运行 python 脚本而不需要权限或特殊安装?