Mysql

如何在 mysql 中連接兩個表,以便每當我將數據添加到表 1 時,表 2 也會更新?

  • February 6, 2022

這是創建我的第一個表的程式碼

create table Todo_tbl (
id INT auto_increment,
person VARCHAR(45) ,
task VARCHAR(45) ,
duration INT(4),
deadline_day VARCHAR(2),
deadline_month VARCHAR(2),

PRIMARY KEY(id)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

insert into Todo_tbl values(1,'John', 'dust the floors', 40,04,03);
insert into Todo_tbl values(2,'Matt', 'do the dishes', 15,02,02);
insert into Todo_tbl values(3,'Mary', 'dusting', 40,03,02);
insert into Todo_tbl values(4,'Chloe', 'cleaning the windows', 75,04,05);
insert into Todo_tbl values(5,'John', 'wash the floors', 60,03,03);
insert into Todo_tbl values(6,'Bridget', 'take out the trash', 15,03,03);
insert into Todo_tbl values(7,'Matt', 'do the laundry', 18,02,02);
insert into Todo_tbl values(8,'Bridget', 'water the plants', 15,03,03);

這是我的第二個表的程式碼:

create table Statistics_tbl (
SELECT person, SUM(duration) as total_duration FROM Todo_tbl GROUP BY person
);

如您所見,表一是基於 Todo_tbl 中的數據建構的。問題是每當我向 Todo_tbl 添加數據時,Statistics_tbl 中的值都不會改變。如何連接這兩個表,以便每當我向 Todo_tbl 輸入新數據時,Statistics_tbl 會自動做出反應?

我認為更好的方法是創建 評論中提到的@Akina的視圖。

create view Statistics_tbl as SELECT person, 
                             SUM(duration) as total_duration 
                             FROM Todo_tbl 
                             GROUP BY person;

您可以將其用作表格:

select * from Statistics_tbl;

結果:

person  total_duration
John       100
Matt       33
Mary       40
Chloe      75
Bridget    30

引用自:https://dba.stackexchange.com/questions/307079