How to implement tagging system similar to SO in php/mysql?

前端 未结 3 1495
再見小時候
再見小時候 2021-01-30 18:51

I\'m coding a website in PHP/MySQL and I\'d like to implement a similar to stackoverflow tagging engine. I have 3 relevant tables in DB: 1. Items 2. Tags 3. ItemTagMap (maps tag

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 19:48

    Assuming:

    • Item (id);
    • Tag (id, name) with index on name;
    • ItemTag (item_id, tag_id).

    then:

    SELECT t.name
    FROM Tag t
    WHERE EXISTS (SELECT 1 FROM ItemTag WHERE item_id = 1234)
    ORDER BY t.name
    

    Nothing intensive about that. This is similar but my guess is it would be slower:

    SELECT t.name
    FROM Tag t
    WHERE t.id IN (SELECT tag_id FROM ItemTag WHERE item_id = 1234)
    ORDER BY t.name
    

    This can be done as a join as well:

    SELECT DISTINCT t.name
    FROM Tag t
    JOIN ItemTag i WHERE i.tag_id = t.id
    WHERE i.item_id = 1234
    ORDER BY t.name
    

    I think the first one will be faster but as is always the case with SQL, it's worth testing (on a sufficiently sized data set).

    The above have been done to list the tags for a single item. You want a composite set of tags for search results. That's not difficult from the above but it depends on how you get your search results.

提交回复
热议问题