简体   繁体   中英

SQL Foreign and Primary Keys

This may be a dumb question, but I am really new to SQL database and I would like to create a SQL database that contains 2 tables, for example;

Table 1:

AccountID,

AccountUsername,

AccountPassword,

Account ID would be the primary key.

Table 2:

AccountID

Calculation

TotalCalculation

AccountID would be the foreign key.

Everytime I update the AccountID in Table 1, it does not show data for AccountID in Table 2, I'm really new to database and I don't know is it possible to do or not.

What I would like to achieve is:

Table 1:

AccountID = 1;

AccountUsername = 'TestUsername'

AccountPassword = 'TestPassword'

Table 2:

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

Calculation = 123.123

TotalCalculation = 1234.1234

If you want to automatically update the accountid in table2 when you update it in table1 then create a FK on table2 with an on update cascade clause for example

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 中的帐户。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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