如何从另一个表设计一个Tag表?

发布于 2024-12-07 06:13:24 字数 282 浏览 1 评论 0原文

我正在设计一个软件,它将使用标签来识别类似于 StackOverflow 的帖子,但有一些区别。

标签必须动态加载(就像这里一样),但来自各种不同的表,因为它将用于识别。

示例:标签 Brazil 标识 country 表 中的一个国家/地区,标签 Monday 标识 week day 表 中的一天代码>.

我需要了解如何在数据库中设计它。如何加载所有表中的标签,同时识别数据所属的正确表。

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 country 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨巷深深 2024-12-14 06:13:25

这可能会满足您的要求:

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 ...;

然后您可以创建其他表并将它们添加到视图中。当您标记其他表时,您会将标记的名称和来源视为主键并引用此视图,如下所示:

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

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

不幸的是,无法从表 foo_tags 定义外键 到上面定义的视图tags

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文