Home > Software design >  SQL query (many to many )
SQL query (many to many )

Time:08-04

I have a table of notes and a table of tags. They are connected via an additional table. Each note can have multiple tags and each tag can have multiple notes. It looks like this:

enter image description here

I can't figure out how to write a query correctly.

Please help me get all the tags of one note. (SELECT * FROM tags ...)

CodePudding user response:

You just need to join the tables:

SELECT *
FROM notes n
   LEFT OUTER JOIN notes_tags nt
      ON n.note_id = nt.note_id
   LEFT OUTER JOIN tags t 
      ON nt.tag_id = t.tag_d
WHERE n.note_id = <some note you are interested in>

Using a LEFT OUTER JOIN since I suspect some notes might have 0 tags. This will still spit out the note record but with no tag information in the row.

  • Related