簡體   English   中英

SQL 外鍵和主鍵

[英]SQL Foreign and Primary Keys

這可能是一個愚蠢的問題,但我對SQL database真的很SQL database ,我想創建一個包含 2 個表的SQL database ,例如;

表格1:

AccountID,

AccountUsername,

AccountPassword,

帳戶 ID 將是主鍵。

表 2:

AccountID

Calculation

TotalCalculation

AccountID 將是外鍵。

每次我更新表 1 中的AccountID時,它都沒有顯示表 2 中 AccountID 的數據,我對數據庫真的很陌生,我不知道是否可以這樣做。

我想實現的是:

表格1:

AccountID = 1;

AccountUsername = 'TestUsername'

AccountPassword = 'TestPassword'

表 2:

AccountID = 1; - This is updated whenever I update the AccountID in Table 1.

Calculation = 123.123

TotalCalculation = 1234.1234

如果要在 table1 中更新時自動更新 table2 中的 accountid,則在 table2 上創建一個 FK,例如使用 on update cascade 子句

drop table if exists t,t1;
create table t
(accountid int primary key);

create table t1
(accountid int,
foreign key fk1(accountid) references t(accountid) on update cascade
);

insert into t values (1),(2);
insert into t1 values (1);

update t
    set accountid = 3 where accountid = 1;

select * from t;
+-----------+
| accountid |
+-----------+
|         2 |
|         3 |
+-----------+
2 rows in set (0.01 sec)

select * from t1;
+-----------+
| accountid |
+-----------+
|         3 |
+-----------+
1 row in set (0.00 sec)

如果您想在創建帳戶時更新默認計算和總計計算 將觸發器添加到表 1 以添加/更新表 2 中的帳戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM