简体   繁体   English

SQL表设计样式:

[英]SQL Table Design Style:

I'm a beginner in SQL and would like to make sure I'm approaching the proper architecture design for a database I'm creating. 我是SQL的初学者,想确保自己正在为要创建的数据库进行正确的体系结构设计。

I've come up with a simpler example of my overall design. 我提出了一个简单的总体设计示例。

Say I have a table: 说我有一张桌子:

mysql> create table Animals(name varchar(255), flags int);

where flags holds truth values for properties of an animal, such as Carnivore, Amphibian, Mammal, et cetera. 其中的标记保存着动物(例如肉食动物,两栖动物,哺乳动物等)的特性的真值。

Since int is just a binary number, I could could use XOR to filter through these flags for what I want matched. 由于int只是一个二进制数,因此我可以使用XOR筛选这些标志以查找所需的内容。

Or I could have a table like this: 或者我可以有一个像这样的表:

mysql> create table Animals(name varchar(255), flag1 bit, flag2 bit, flag3 bit);

My concern for this is: 我对此的关注是:

Are bits wasted using this approach, or if I have flag1 - flag8, one byte will be used? 使用这种方法是否浪费了比特,或者如果我有flag1-flag8,将使用一个字节吗?

Ultimately: 最后:

Is this even an appropriate way to go about doing this sort of design? 这甚至是进行这种设计的合适方法吗? If not, some guidance would really be appreciated. 如果不是这样,一定会得到一些指导。

I understand that I could have a ton of tables for say, Carnivore, Amphibian, Mammal, et cetera, which would have entries with the same names at mammals, which would avoid my want to use flags, but that almost seems wasteful to me. 我知道我可以有很多桌子,例如食肉动物,两栖动物,哺乳动物等,它们在哺乳动物中会有相同名称的条目,这样可以避免我想要使用标志,但是这对我来说似乎很浪费。

To properly normalize, you need to create another table: 为了正确规范化,您需要创建另一个表:

Animals (animalID, animalName)
Flags (flagID, flagName)
AnimalFlags (animalID, flagID)

This will allow you to have as many or as few flags per animal as you want without the mess of having to parse with XOR. 这样一来,您就可以根据需要在每只动物上拥有任意数量的标志,而不必用XOR进行解析。

You would be better off creating one table for animals, another for categories and another for assigning an animal to a category. 您最好为一个动物创建一个表,为类别创建另一个表,再为一个动物分配一个类别。

create table Animals(AnimalID int, AnimalName varchar(255));
create table Categories(CategoryID int, CategoryName varchar(255));
create table AnimalCategoryLink(AnimalID int, CategoryID int);

This will give you the flexibility of adding as many categories as you like and also you can add categories at runtime. 这将使您可以灵活地添加任意数量的类别,也可以在运行时添加类别。

You can use a JOIN between these tables to filter as needed. 您可以在这些表之间使用JOIN进行过滤。

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

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