开发者

How to design a Tag table from another tables?

开发者 https://www.devze.com 2023-04-08 15:11 出处:网络
I\'m designing a software that will use tags to identify posts similar to StackOverflow, but with some differences.

I'm designing a software that will use tags to identify posts similar to StackOverflow, but with some differences.

The tags must be loaded dinamically (like here), but come from various different tables because it will be used for identification.

Example: the tag Brazil identifies an cou开发者_开发问答ntry in the country table, the tag Monday identifies a day in the week day table.

I need an idea of how design this in the database. How have the tags from all tables loading, but identifying the correct table the data belongs.


This might do what you want:

CREATE TABLE countries (
  name VARCHAR PRIMARY KEY,
  ...
);

CREATE TABLE weekdays (
  name VARCHAR PRIMARY KEY,
  ...
);

CREATE VIEW tags AS 
(SELECT name AS tag, 'countries' AS source
 FROM countries) 
UNION ALL
(SELECT name AS weekdays, 'weekdays' AS source
 FROM weekdays) 
UNION ALL ...;

Then you can make additional tables and add them to the view. When you tag some other table, you'll treate the name and source of the tag as the primary key and refer to this view, like so:

CREATE TABLE foo (
  id SERIAL PRIMARY KEY,
  ...
);

CREATE TABLE foo_tags (
  foo_id INTEGER REFERENCES foo,
  tag_name VARCHAR,
  tag_source VARCHAR
);

Unfortunately, it isn't possible to define a foreign key from the table foo_tags to the view tags defined above.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号