I have a database with two main tables notes
and labels
. They have a many-to-many relationship (similar to how stackoverflow.com has questions with labels). What I am wondering is how can I search for a note using multiple labels using SQL?
For example if I have a note "test" with three labels "one", "two", and "three" and I have a second note "test2" with labels "one" and "two" what is the SQL query that will find all the notes that are associated with labels "one" and "two"?
If you just need a list, you can use
where exists
to avoid duplication. If you have multiple tags against a node in your selection criteria you will get duplicate rows in the result. Here's an example ofwhere exists
:To obtain the details of notes that have both labels 'One' and 'Two':
You say nothing about how this many-to-many relationship is realised. I assume that the labels table has is Labels(noteid: int, label: varchar) - with a primary key spanning both?
Replace with your column names, and insert the proper placeholders for the labels.
Assuming you have a normalized database, you should have another table in between
notes
andlabels
You should then use an
inner join
to join the tables togetherlabels
table with the bind-table (many-to-many table)notes
table with the previous queryExample:
select * from ((labels l inner join labels_notes ln on l.labelid = ln.labelid) inner join notes n on ln.notesid = n.noteid)
That way, you have connected both tables together.
Now what you need to add is the
where
clause...but I'll leave that up to you.Something like this... (you'll need another link table)
Edit: the NoteLabel table will have two columns, noteId and labelId, with a composite PK.
Note: I haven't actually tested this. It also assumes you have a many-to-many table named notes_labels, which may not be the case at all.
If you just want the notes that having any of the labels, it's be something like this
If you want the notes that have ALL of the labels, there's a little extra work
? being a SQL placeholder and 2 being the number of tags you were searching for. This is assuming that the link table has both ID columns as a compound primary key.