0

我需要存储这个关系:

domain -> tag1, tag2, tag3 .... tagN

到一个 msql 表。

我想我只会有两个这样的字段

domain | tag_arary

实际数据可能是:

facebook.com | [social, networking, web, foo1, foo2 ]

或者另一种方式,将设置标签的最大数量,并为每个标签设置一个字段:

结构

domain | tag1 | tag2 | tag3 

实际数据

facebook.com | social | networking | web | foo1 | foo2 

实现这一点的最佳方法是什么。

请注意,我需要添加标签和删除标签。

谢谢

4

1 回答 1

1

This is probably the most flexible way for the long run, as it's much easier to query/update/delete the tags. You might want to give id to the domains table though, as it would be much faster in terms of searching on integer field.

CREATE TABLE domains (
 domain VARCHAR(255) PRIMARY KEY
);

# table to store all your domain names
INSERT INTO domains (domain) VALUES ('www.facebook.com');

# table to store all the tags you want to have for your application
CREATE TABLE tags (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
tag_name VARCHAR(255)
);

INSERT INTO tags (tag_name) VALUES ('social');
INSERT INTO tags (tag_name) VALUES ('networking');

# Then, you can store all the tags related to a domain in domain_tags table
# It provides one-to-many relationship between a domain and tags.
CREATE TABLE domain_tags (
    domain VARCHAR(255),
    tag_id INTEGER
);

INSERT INTO domain_tags (domain, tag_id) VALUES ('www.facebook.com', 1);
INSERT INTO domain_tags (domain, tag_id) VALUES ('www.facebook.com',2);

# Whenever you want to get the tags for a domain, simply join the tables together
# and query based on your domain name.
SELECT tag_name
FROM domains d
INNER JOIN domain_tags dt ON d.domain= dt.domain
INNER JOIN tags t ON t.id= dt.tag_id
WHERE d.domain='www.facebook.com';
于 2012-08-12T22:25:51.053 回答