问题
I'm pretty new to working with SQL but I've come across this question on Stack Overflow for working with tags.
Recommended SQL database design for tags or tagging
This led me to create the following tables in my database:
Doc
---------------------------------------------------------------
| Doc Id (PK)(int) | Doc Title (varchar) | Doc Link (varchar) |
---------------------------------------------------------------
| 1 | Printing | http://example.com |
---------------------------------------------------------------
| 2 | Format | http://example.com |
---------------------------------------------------------------
Tag
--------------------------------------
| Tag Id (PK)(int) | Title (varchar) |
--------------------------------------
| 1 | print |
--------------------------------------
| 2 | guide |
--------------------------------------
| 3 | support |
--------------------------------------
DocTag
---------------------------------
| DocId (int) | TagId (varchar) |
---------------------------------
| 1 | 1, 3 |
---------------------------------
| 2 | 2, 3 |
---------------------------------
However, I cannot create foreign keys between the DocTag
table and the other two because I need to create an array of sorts in the TagId
of DocTag
because one doc can have many tags. I am getting an error when trying to create the primary key and I assume it's because of the varchar variable in TagId
.
What are some suggestions for overcoming this?
回答1:
DocTag
---------------------------------
| DocId (int) | TagId (int) |
---------------------------------
| 1 | 1 |
---------------------------------
| 1 | 3 |
---------------------------------
| 2 | 2 |
---------------------------------
| 2 | 3 |
---------------------------------
Foreign keys must match the data type of the column they reference.
Each foreign key reference must be a single value. No comma-separated lists.
Put each TagId value on a row of its own, even though you have to repeat the DocId.
See my answer to: "Is storing a delimited list in a database column really that bad?"
来源:https://stackoverflow.com/questions/42043739/setting-up-foreign-key-with-an-array-of-integers