Vladislav
Vladislav

Reputation: 476

SQL query (many to many )

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 ...)

Upvotes: 0

Views: 49

Answers (1)

JNevill
JNevill

Reputation: 50034

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.

Upvotes: 1

Related Questions