标签或标记的数据库设计

Database design for tags or tagging

如何轻松地将项目标签存储在数据库中?

每件商品都有多个标签。我已经阅读了一些关于有效方法的答案:

  1. What is the most efficient way to store tags in a database?
  2. Recommended SQL database design for tags or tagging

但我认为对此有更好的解决方案。为什么我们不能简单地将标签作为每个项目的长字符串包含在内?

 Table : Brand_Shops
 Columns : brand_id, brand_name, content, tags

示例:

1 || Nike ||  shoes bags sports football soccer t-shirts track-pants
2 ||  GAP || wallets t-shirts jeans shoes perfumes

这没有原子性但是完全符合标记的目的。如果必须添加新品牌,只需添加新标签即可。因此,获取它也将非常容易。我不明白为什么这不是一个有效的解决方案。

I don't understand why this is not an efficient solution.

效率低下,因为您必须为每个查询检索并 break/search 该字符串。

当你做类似(如你的链接中所述)的事情时 Three tables (one for storing all items, one for all tags, and one for the relation between the two) 然后你可以使用关系数据库的真正力量,索引.

不用将每个字符串分解成一个标签或一组标签……这已经完成了;你只是得到你想要的。因此,如果您要搜索 "shoes",那么它会直接搜索到那里(使用索引可能是 log n 或更快),并且 Nike 和 GAP 都会搜索 returns。无论你有多少标签,无论你有多少公司,它都会这样做。

使用 3-table 系统,您可以预先完成所有艰苦的工作,然后只需进行查找。

如果您打算 运行 在本地或针对有限数量的用户,您的解决方案可能没问题。它也更容易编码。
一旦您的查询开始花费超过几秒钟的时间,您可能想要更新您的标记系统。如果你这样做,单独写搜索代码以防你需要撕掉它。


来自评论的问题:

Can you give an example of a 3 table system that is normalized with atomicity

当然可以。
你基本上要求第三范式,这是我通常的目标。 (我承认我经常不制作 3NF,因为我进行了优化;例如,将邮政编码与地址一起存储——如果你不在学校,那是更好的选择)

--Sample SQL whosebug.com/questions/50793168/database-design-for-tags-or-tagging/50818392
IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'ChrisC') 
BEGIN
 EXEC sys.sp_executesql N'CREATE SCHEMA [ChrisC] AUTHORIZATION [dbo]'
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ChrisC].[Brands]') AND type in (N'U'))
     AND NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ChrisC].[BrandTags]') AND type in (N'U'))
     AND NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[ChrisC].[Tags]') AND type in (N'U'))
 BEGIN
  CREATE TABLE [ChrisC].[Brands]([pkBrand] [int] IDENTITY(101,1) NOT NULL,[Name] [varchar](40) NULL) ON [PRIMARY]
  INSERT INTO [ChrisC].[Brands]([Name])VALUES('Nike'),('GAP')
  CREATE TABLE [ChrisC].[BrandTags]([pk] [int] IDENTITY(1,1) NOT NULL,[Brand] [int] NULL,[Tag] [int] NULL) ON [PRIMARY]
  INSERT INTO [ChrisC].[BrandTags]([Brand],[Tag])VALUES
    (101,201),(101,202),(101,203),(101,204),(101,205),(101,206),(101,207),
    (102,208),(102,209),(102,203),(102,207),(102,210)
  CREATE TABLE [ChrisC].[Tags]([pkTag] [int] IDENTITY(201,1) NOT NULL,[Tag] [varchar](40) NULL) ON [PRIMARY]
  INSERT INTO [ChrisC].[Tags]([Tag])VALUES
    ('bags'),('football'),('shoes'),('soccer'),('sports'),('track-pants'),('t-shirts'),('jeans'),('perfumes'),('wallets')
  SELECT b.[Name], t.Tag 
  FROM chrisc.Brands b 
  LEFT JOIN chrisc.BrandTags bt ON pkBrand = Brand
  LEFT JOIN chrisc.Tags t ON bt.Tag = t.pkTag
  WHERE b.[Name] = 'Nike'
  -- Stop execution here to see the tables with data
  DROP TABLE [ChrisC].[Brands]
  DROP TABLE [ChrisC].[BrandTags]
  DROP TABLE [ChrisC].[Tags]
 END
 IF  EXISTS (SELECT * FROM sys.schemas WHERE name = N'ChrisC') DROP SCHEMA [ChrisC]
END