Mysql SQL外键和主键
这可能是一个愚蠢的问题,但我对Mysql SQL外键和主键,mysql,sql,database,Mysql,Sql,Database,这可能是一个愚蠢的问题,但我对SQL数据库真的很陌生,我想创建一个SQL数据库,它包含两个表,例如 表1: AccountID, AccountUsername, AccountPassword, AccountID Calculation TotalCalculation AccountID = 1; AccountUsername = 'TestUsername' AccountPassword = 'TestPassword' AccountID = 1; - This
SQL数据库
真的很陌生,我想创建一个SQL数据库
,它包含两个表,例如
表1:
AccountID,
AccountUsername,
AccountPassword,
AccountID
Calculation
TotalCalculation
AccountID = 1;
AccountUsername = 'TestUsername'
AccountPassword = 'TestPassword'
AccountID = 1; - This is updated whenever I update the AccountID in Table 1.
Calculation = 123.123
TotalCalculation = 1234.1234
帐户ID将是主键
表2:
AccountID,
AccountUsername,
AccountPassword,
AccountID
Calculation
TotalCalculation
AccountID = 1;
AccountUsername = 'TestUsername'
AccountPassword = 'TestPassword'
AccountID = 1; - This is updated whenever I update the AccountID in Table 1.
Calculation = 123.123
TotalCalculation = 1234.1234
AccountID将是外键
每次我更新表1中的AccountID时,它都不会在表2中显示AccountID的数据,我对数据库非常陌生,不知道是否可以这样做
我希望达到的目标是:
表1:
AccountID,
AccountUsername,
AccountPassword,
AccountID
Calculation
TotalCalculation
AccountID = 1;
AccountUsername = 'TestUsername'
AccountPassword = 'TestPassword'
AccountID = 1; - This is updated whenever I update the AccountID in Table 1.
Calculation = 123.123
TotalCalculation = 1234.1234
表2:
AccountID,
AccountUsername,
AccountPassword,
AccountID
Calculation
TotalCalculation
AccountID = 1;
AccountUsername = 'TestUsername'
AccountPassword = 'TestPassword'
AccountID = 1; - This is updated whenever I update the AccountID in Table 1.
Calculation = 123.123
TotalCalculation = 1234.1234
如果要在表1中更新accountid时自动更新表2中的accountid,请在表2中创建一个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中的帐户。您试图解决什么问题?你想做什么?如果你在T1中插入一个新行,你需要在T2中插入一个具有相同AccountID的行。表2中的主键是什么?对不起,我忘了添加@草莓,但是会有一个名为CalculationID的列,它将是表2的主键。请注意,提供了一个编辑按钮,看看是否可以提供一个更全面的示例。见: