简体   繁体   English

SQL'加入'2个主键到1

[英]SQL 'join' 2 primary keys to 1

I have 2 tables: 我有2张桌子:

PrimKey
001
002

And: 和:

ID | ForeignKey
a  | 001
b  | 002
c  | 002

I want to delete, let's say, row 002 and 'bind' all 002 foreign keys to 001, so it will look like: 我想删除,比方说,行002和'绑定'所有002外键到001,所以它看起来像:

PrimKey
001

And: 和:

ID | ForeignKey
a  | 001
b  | 001
c  | 001

FK constraints do not allow me to do UPDATE + DELETE. FK约束不允许我做UPDATE + DELETE。 Any tip where to dig? 任何提示在哪里挖?

You have to do it from the other direction. 你必须从另一个方向去做。 Change the rows in the second table to point to a different PK in the first table; 更改第二个表中的行以指向第一个表中的不同PK; then when there are no references to row002, you can delete it. 那么当没有对row002的引用时,你可以删除它。

您也可以尝试begin transactionupdatedeletecommit

if you have no control over the database schema, then you must manually delete as pointed out by Jeremy. 如果您无法控制数据库架构,则必须按照Jeremy的指示手动删除。

If you do have control, you can add a foreign key relationship between the tables and add a "cascade delete" constraint in the relationship detail. 如果确实有控件,则可以在表之间添加外键关系,并在关系详细信息中添加“级联删除”约束。 You do this by going to the table design of the table with foreign keys and right-clicking to choose "Relationships." 您可以通过使用外键转到表的表设计并右键单击以选择“关系”来完成此操作。 Then you choose "Add" and go to the section for defining the table and columns. 然后选择“添加”并转到定义表和列的部分。 Click the button with the three dots and you will be able to choose the parent table for the relationship and then you can select the columns for creating the relationship. 单击带有三个点的按钮,您将能够选择关系的父表,然后您可以选择用于创建关系的列。 Finally, in the relationships screen you locate the insert/update specification section to indicate "cascade" on delete. 最后,在关系屏幕中,您可以找到插入/更新规范部分,以指示删除时的“级联”。 (There is an alter table statement for this, too, but sometimes it's just faster to use the GUI.) (对此也有一个alter table语句,但有时候使用GUI会更快。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM