mysql - SQL如何引用变量列

标签 mysql sql variables reference

我正在尝试创建一个壁纸共享库,我希望我的访问者能够对壁纸和文章发表评论。

假设我有以下表格:

Wallpaper
- id
- name
- etc...

Article
- id
- title
- etc...

Comment
- id
- text

我希望评论与独特的墙纸或独特的文章相关联。

我想过这样继承:

Commentable
- id

Article
- id references Commentable.id
- etc...

Wallpaper
- id references Commentable.id
- etc...

Comment
- id
- commented references commentable.id

但是这个方法看起来很笨重而且不太好。

我也想过:

Wallpaper
- id
- name
- etc...

Article
- id
- title
- etc...

Comment
- id
- commented references either Wallpaper.id or Article.id

但是没有办法知道关联的东西是墙纸还是文章。

此外,我想使用 MyISAM 而不是 InnoDB,因为我将使用 5.1 MySQL 将其上传到免费的 Web 主机服务。

你知道这样做的任何明确方法吗?提前致谢。

编辑:感谢大家的回答。

最佳答案

两种选择:

选项一

Wallpaper
- id
- name

Article
- id
- title

Comment
- id
- wallpaper_id <== FK
- article_id   <== FK

优点:参照完整性
缺点:您必须修改架构才能评论其他实体类型

方案二

Wallpaper
- id
- name

Article
- id
- title

Comment
- id
- entity_id <== either a wallpaper id or article id
- entity_type <== one of 'wallpaper' or 'article' (use lookup table if you wish)

优点:您无需修改​​架构即可评论其他实体类型
缺点:没有参照完整性(尽管可以通过触发器强制执行)

关于mysql - SQL如何引用变量列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12376642/

相关文章:

bash - if 语句内的变量替换

Python pymssql连接字符串使用变量

在 Select 子句中使用计算字段和子查询的 C# LINQ 查询

mysql - 返回MySQL中一个表的id出现在另一个表中的次数(包括0次)

mysql - 将两个单独的 SQL 查询合并为一个

sql - 使用 NOT EXISTS 重写查询的指导

php - MySql 查询错误

mysql - 使用 `.createSQLQuery` 截断后 spring/hibernate 不会回滚事务

mysql - 创建Mysql日期时间列,默认为0000-00-00

variables - 如何在 JMeter 中获取线程和采样器名称