您需要考虑一个称为“规范化”的数据库术语。规范化意味着一切都在数据库中,不应该列出两次,而是根据需要重用。人们最常犯的错误是不问或不考虑未来会发生什么,他们建立了一个几乎没有规范化、对大型数据类型消耗大量内存、没有做种子、完全不灵活和以后改变要付出很大的代价,因为它是在没有考虑未来的情况下做出的。
标准化有很多级别,但最一致的事情是考虑一个简单的例子,我可以给你解释一些可以在以后应用于更大的事情的简单概念。这是假设您可以访问 SQL 管理工作室、SSMS,但是如果您使用的是 MYSQL 或 Oracle,原理仍然非常相似,评论部分将显示我的意思。如果您有 SSMS,则可以自行运行此示例,只需将其粘贴并按 F5。如果您不只是查看评论部分,尽管这些概念在实践中比试图想象它们的含义更好。
Declare @Everything table (PersonID int, OrderID int, PersonName varchar(8), OrderName varchar(8) );
insert into @Everything values (1, 1, 'Brett', 'Hat'),(1, 2, 'Brett', 'Shirt'),(1, 3, 'Brett', 'Shoes'),(2,1,'John','Shirt'),(2,2,'John','Shoes');
-- very basic normalization level in that I did not even ATTEMPT to seperate entities into different tables for reuse.
-- I just insert EVERYTHING as I get in one place. This is great for just getting off the ground or testing things.
-- but in the future you won't be able to change this easily as everything is here and if there is a lot of data it is hard
-- to move it. When you insert if you keep adding more and more and more columns it will get slower as it requires memory
-- for the rows and the columns
Select Top 10 * from @Everything
declare @Person table ( PersonID int identity, PersonName varchar(8));
insert into @Person values ('Brett'),('John');
declare @Orders table ( OrderID int identity, PersonID int, OrderName varchar(8));
insert into @Orders values (1, 'Hat'),(1,'Shirt'),(1, 'Shoes'),(2,'Shirt'),(2, 'Shoes');
-- I now have tables storing two logic things in two logical places. If I want to relate them I can use the TSQL language
-- to do so. I am now using less memory for storage of the individual tables and if one or another becomes too large I can
-- deal with them isolated. I also have a seeding record (an ever increasing number) that I could use as a primary key to
-- relate row position and for faster indexing
Select *
from @Person p
join @Orders o on p.PersonID = o.PersonID
declare @TypeOfOrder table ( OrderTypeID int identity, OrderType varchar(8));
insert into @TypeOfOrder values ('Hat'),('Shirt'),('Shoes')
declare @OrderBridge table ( OrderID int identity, PersonID int, OrderType int)
insert into @OrderBridge values (1, 1),(1,2),(1,3),(2,2),(2,3);
-- Wow I have a lot more columns but my ability to expand is now pretty flexible I could add even MORE products to the bridge table
-- or other tables I have not even thought of yet. Now that I have a bridge table I have to list a product type ONLY once ever and
-- then when someone orders it again I just label the bridge to relate a person to an order, hence the name bridge as it on it's own
-- serves nothing but relating two different things to each other. This method takes more time to set up but in the end you need
-- less rows of your database overall as you are REUSING data efficiently and effectively.
Select Top 10 *
from @Person p
join @OrderBridge o on p.PersonID = o.PersonID
join @TypeOfOrder t on o.OrderType = t.OrderTypeID