How to implement tag counting

前端 未结 4 1476
再見小時候
再見小時候 2021-02-03 13:46

I have my tags desinged like this in my database:

Table: Item 
Columns: ItemID, Title, Content 

Table: Tag 
Columns: TagID, Title 

Table: ItemTag 
Columns: Ite         


        
相关标签:
4条回答
  • 2021-02-03 14:22
    select t.Title, count(it.TagID) as TagCount
    from Tag t
      inner join ItemTag it on t.TagID = it.TagID
      inner join Item i on it.ItemID = i.ItemID
    where i.ItemID = @currentItemID -- optional, if you only want current page
    group by t.Title
    
    0 讨论(0)
  • 2021-02-03 14:31

    You can use another column in Item to store tag count and synchronize it when add or remove tags.

    0 讨论(0)
  • 2021-02-03 14:34
    SELECT title, count(*) FROM tag
    JOIN itemtag ON itemtag.tagid = tag.tagid
    GROUP BY title
    
    0 讨论(0)
  • 2021-02-03 14:35

    Add another column in the table Tag that work as counter. When you add or remove a tag from an item you update the counter (in other words, when add a row on Itemtag increment the counter on Tag table, when remove decrement the counter)

    add tag to item:

    INSERT INTO Itemtag (itemid,tagid) VALUES ('$itemid','$tagid');
    UPDATE Tag SET counter=counter+1 WHERE tagid='$tagid';
    

    remove tag from item

    DELETE FROM Itemtag WHERE itemid='$itemid' AND tagid='$tagid';
    UPDATE Tag SET counter=counter-1 WHERE tagid='$tagid';
    

    retrieve item tags with counter

    SELECT t.title, t.counter FROM Itemtag AS it JOIN Tag AS t ON t.idtag=it.tagid 
    WHERE it.itemid='$itemid'
    
    0 讨论(0)
提交回复
热议问题