python - sqlalchemy 创建外键?

标签 python sql sqlalchemy

我在表字符串中有一个复合 PK(整数 id、varchar(2) lang)

我想创建一个 FK,仅用于其他表中 PK 的 id 一半。这意味着字符串表(翻译)中可能有许多行与 FK 匹配。我只需要存储 id,并由数据库维护引用完整性。

这可能吗?如果是这样,怎么办?

最佳答案

这是来自 wiki

The columns in the referencing table must be the primary key or other candidate key in the referenced table. The values in one row of the referencing columns must occur in a single row in the referenced table.

假设你有这个:

id | var            
1  |  10            
1  |  11          
2  |  10

外键必须引用所引用表中的恰好一行。这就是为什么它通常引用主键。

在您的情况下,您需要创建另一个 Table1(id) 来存储 ids 并使列成为唯一/主键。当前表中的 id 列不是唯一的 - 您不能在您的情况下使用它...因此您创建一个 Table1(id - 主键)并将当前表中的 id 设为外键表1。现在您可以在 Table1 中为 id 创建外键,并且当前表中的主键就可以了。

关于python - sqlalchemy 创建外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1350121/

相关文章:

python - 从 statusItem 启动的 NSWindow menuItem 不显示为事件窗口

python - "can' t escape _io.BufferedRandom to binary"试图将图像插入 BYTEA 列时

sql - 从 Oracle DB 中查找幽灵约束

Python Pandas - 使用 to_sql 以 block 的形式写入大数据帧

python - Flask WTForms - 基于多个表单字段的自定义验证器

python - 如果涉及抽象表,SQLAlchemy 索引会导致 "Can' t 将未命名列添加到列集合中

python - AWS boto3 Athena 查询结果未保存到本地路径

python - 从列表中读入MySql

sql - 所需的列百分比

php - 合并多行中的一列