L
L
lafayette2010-11-29 10:36:53
SQL
lafayette, 2010-11-29 10:36:53

Selecting records from the database according to the list of labels specified in another table?

MySQL has a table with records, also in a separate table are “record id” - “tag id”, which indicate which tags the indicated record has.
You must select entries by user-defined tags. In this case, there can be several tags in the request, and in this case, all records containing at least one of the tags listed in the request are selected.
The option in which a separate field is created for each label in the record table is not suitable, because. if necessary, you need to add a new label without changes in the sql query code.
Tell me, what sql-query to make such a selection?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xE0, 2010-11-29
@lafayette

select Record from TableWithRecords where idRecords in (select idRecords from TableTagged where idTag = 'desired tag')

S
Servn, 2010-11-29
@Servn

SELECT r*
    FROM Records
    INNER JOIN Record_Tag rt ON rt.record_id = r.id
    INNER JOIN Tag t ON t.id = rt.tag_id
    WHERE t.name IN ('tag1','tag2','tag3,...,'tagN')

Selects all records (not unique) by tags, in order to select unique you need to add DISTINCT, or grouping, depending on how you are going to use this data.

0
0xE0, 2010-11-29
@0xE0

Do you want each tag to be a separate field in the final table? Or a separate entry?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question