7

我的数据库中有这样设计的标签:

Table: Item 
Columns: ItemID, Title, Content 

Table: Tag 
Columns: TagID, Title 

Table: ItemTag 
Columns: ItemID, TagID



//example -- this is the right sidebar of stackoverflow
c# × 59279
sql × 14885
asp.net-mvc × 9123
linq × 4337
tags × 339

如果我想知道每个标签的计数,例如 stackoverflow 如何计算他们的标签,我该怎么做?我会执行什么样的查询。我对常规 sql 和 linq 都开放

4

4 回答 4

4

在表标签中添加另一列作为计数器。当您从项目中添加或删除标签时,您会更新计数器(换句话说,当在 Itemtag 上添加一行时,增加 Tag 表上的计数器,当删除时减少计数器)

为项目添加标签:

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

从项目中删除标签

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

用计数器检索项目标签

SELECT t.title, t.counter FROM Itemtag AS it JOIN Tag AS t ON t.idtag=it.tagid 
WHERE it.itemid='$itemid'
于 2010-01-23T09:42:40.847 回答
3
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
于 2010-01-23T08:48:36.503 回答
0
SELECT title, count(*) FROM tag
JOIN itemtag ON itemtag.tagid = tag.tagid
GROUP BY title
于 2010-01-23T09:04:44.863 回答
0

您可以使用另一列Item来存储标签计数并在添加或删除标签时同步它。

于 2010-01-23T08:50:40.883 回答