简体   繁体   English

如果找不到参考表中添加记录的最佳方法

[英]Best way to add record in reference table if not found

I'm trying to implement a simple tag system in my app. 我正在尝试在我的应用程序中实现一个简单的标签系统。 When users want to tag an object, they can use existing tags and/or create new tags at the same time. 当用户想要标记对象时,他们可以使用现有标记和/或同时创建新标记。 I have a table 'tag' which just stores the unique tag string value as a PK. 我有一个表“标签”,仅将唯一的标签字符串值存储为PK。 In 'object_tag' I have a FK reference to this column. 在“ object_tag”中,我对此列有FK引用。 In a request from the client there can be multiple tags for one object. 在客户端的请求中,一个对象可以有多个标签。 On the server I will loop through all the tags and store them in 'object_tag'. 在服务器上,我将遍历所有标签并将它们存储在“ object_tag”中。 If the tag doesn't exist in the 'tag' table, it should be inserted first. 如果“标签”表中不存在该标签,则应首先将其插入。

What is the most efficient way to do this? 最有效的方法是什么? I could just check if the tag exists before each insert, but I want to minimize the database I/O. 我可以只在每次插入之前检查标记是否存在,但是我想最小化数据库I / O。

You will need 3 tables as follows: 您将需要3个表,如下所示:

Object - list of objects, primary key oid Tag - list of tags, primary key tid ObjectTag - pairs of oid, tid values Object-对象列表,主键oid Tag-标签列表,主键tid ObjectTag-对oid,tid值

See also: 也可以看看:

Tags: Database schemas 标签:数据库模式

The Problem: You want to have a database schema where you can tag a bookmark (or a blog post or whatever) with as many tags as you want. 问题:您想要一个数据库架构,可以在其中使用所需数量的标签来标记书签(或博客文章或其他内容)。 Later then, you want to run queries to constrain the bookmarks to a union or intersection of tags. 然后,您要运行查询以将书签限制为标签的并集或交集。 You also want to exclude (say: minus) some tags from the search result. 您还想从搜索结果中排除(例如:减去)一些标签。

  • " MySQLicious " solution - uses one denormalized table. MySQLicious ”解决方案-使用一个非规范化表。 MySQLicious imports del.icio.us data into a table with this structure. MySQLicious将具有此结构的del.icio.us数据导入到表中。
  • "Scuttle" solution - Scuttle organizes its data in two tables. “ Scuttle”解决方案-Scuttle将其数据组织在两个表中。 That table “scCategories” is the “tag”-table and has got a foreign key to the “bookmark”-table. 该表“ scCategories”是“ tag”表,并且具有“ bookmark”表的外键。
  • "Toxi Solution" Toxi came up with a three-table structure. “ Toxi解决方案” Toxi提出了一个三表结构。 Via the table “tagmap” the bookmarks and the tags are n-to-m related. 通过表格“ tagmap”,书签和标签是n-m相关的。 Each tag can be used together with different bookmarks and vice versa. 每个标签可以与不同的书签一起使用,反之亦然。 This DB-schema is also used by wordpress . 这个DB模式也被wordpress使用

see also Tagging system: Toxi solution questions 另请参见标记系统:Toxi解决方案问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM