[英]Is ID column always required in SQL?
to be more specific, I've created a news module with a tag system.更具体地说,我创建了一个带有标签系统的新闻模块。 As each tag is unique (you are not allowed, as an admin, to create 2 identical tags), is the id column still useful?
由于每个标签都是唯一的(作为管理员,您不允许创建 2 个相同的标签),id 列仍然有用吗? I guess no, but I was wondering about the performances.
我想没有,但我想知道表演。
id |编号 | mews_title |
mews_title | date... <-------------> news_id |
日期... <-------------> news_id | tag_id <----------> id |
tag_id <----------> id | tag_name
标签名
VS VS
id |编号 | mews_title |
mews_title | date... <-------------> news_id |
日期... <-------------> news_id | tag_tag_name <----------> tag_name
tag_tag_name <----------> tag_name
Thanks a lot!非常感谢!
The performance difference is insignificant.性能差异是微不足道的。
Advantages to using a numeric id
for the tags in your example would be:在您的示例中为标签使用数字
id
的优点是:
These may not be important considerations for your case.对于您的情况,这些可能不是重要的考虑因素。 So no, it's not required to use a numeric
id
.所以不,不需要使用数字
id
。
I also wrote about this in a chapter titled "ID Required" in my book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming .我还在我的书SQL Antipatterns: Avoiding the Pitfalls of Database Programming中题为“需要 ID”的一章中写到了这一点。
Numeric IDs are not required (You could have a table without a primary key), but they are useful:数字 ID 不是必需的(您可以有一个没有主键的表),但它们很有用:
You can specify the tag_name as unique, so two tag_name equals couldn't be inserted.您可以将 tag_name 指定为唯一的,因此无法插入两个等于 tag_name。
You don't even need a table of tags.您甚至不需要标签表。 Just a table with
只是一张桌子
news_id | tag_name
This is a many-to-many mapping between news_ids and tags.这是 news_ids 和标签之间的多对多映射。 Since there is no tag table, the issue of duplicates vanishes.
由于没有标签表,重复的问题就消失了。 The same tag (
tag_name
) can be associated with many news articles, but that is what you want .同一个标签 (
tag_name
) 可以与许多新闻文章相关联,但这正是您想要的。
INSERT INTO Tags (news_id, tag_name)
-- change this to INSERT IGNORE INTO Tags (news_id, tag_name)
so you don't have to worry about getting the same news article tagged the same way twice. INSERT INTO Tags (news_id, tag_name)
-- 将其更改为INSERT IGNORE INTO Tags (news_id, tag_name)
,这样您就不必担心以相同方式标记相同的新闻文章两次。 And have并且有
PRIMARY KEY(news_id, tag_name), -- uniqueness and lookup tags for one article
INDEX(tag_name, news_id) -- For finding all articles for one tag
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.