首页 > 解决方案 > 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 及其所有标签?

标签: mysqlsql

解决方案


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 是连贯的,否则它们之间将没有链接。


推荐阅读