Best practice for storing tags in a database?

前端 未结 3 1282
情书的邮戳
情书的邮戳 2020-12-23 18:28

I developed a site that uses tags (key words) in order to categorize photographs. Right now, what I have in my MySQL database is a table with the following structure:

3条回答
  •  别那么骄傲
    2020-12-23 18:59

    In multi tag search query you will have to hit every tag that is requested. Hence image tag set I has to be a superset of the request tag set U.

    I >= U
    

    To implement this complex comparison in SQL is a bit of challenge as each of the image has to be qualified individually. Given that tags are unique set per image:

    SELECT i.* FROM images AS i WHERE {n} = (
      SELECT COUNT(*) 
      FROM image_tags AS t 
      WHERE t.image_id = i.image_id
        AND t.tag IN ({tag1}, {tag2}, ... {tagn})
    )
    

    Schema:

    CREATE TABLE images (
      image_id varchar NOT NULL,
      PRIMARY KEY (image_id)
    )
    
    CREATE TABLE image_tags (
      image_id varchar NOT NULL,
      tag varchar NOT NULL,
      PRIMARY KEY (image_id, tag)
    )
    

提交回复
热议问题