在Mysql數(shù)據(jù)庫(kù)中,多張表之間的數(shù)據(jù)通常是相互關(guān)聯(lián)的。這些關(guān)聯(lián)有助于實(shí)現(xiàn)復(fù)雜的數(shù)據(jù)查詢和數(shù)據(jù)處理,因此需要建立這些表之間的連接。下面將介紹如何在Mysql中建立五個(gè)表的連接。
CREATE TABLE `employee` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `department_id` int NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `department` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `task` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `employee_id` int NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `attendance` ( `id` int NOT NULL AUTO_INCREMENT, `employee_id` int NOT NULL, `punch_time` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `salary` ( `id` int NOT NULL AUTO_INCREMENT, `employee_id` int NOT NULL, `salary` double NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
以上代碼創(chuàng)建了五個(gè)表:employee(員工表)、department(部門表)、task(任務(wù)表)、attendance(考勤表)、salary(薪資表)。
接下來(lái),我們將通過(guò)使用外鍵將這些表連接起來(lái)。每個(gè)表都有一個(gè)主鍵,通過(guò)主鍵來(lái)建立連接。
ALTER TABLE `employee` ADD CONSTRAINT `employee_department_fk` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE; ALTER TABLE `task` ADD CONSTRAINT `task_employee_fk` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE; ALTER TABLE `attendance` ADD CONSTRAINT `attendance_employee_fk` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; ALTER TABLE `salary` ADD CONSTRAINT `salary_employee_fk` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
以上代碼將建立employee表與department表的連接,task表與employee表的連接,attendance表與employee表的連接,以及salary表與employee表的連接。這些連接將會(huì)在刪除或更新數(shù)據(jù)時(shí)起到作用。
通過(guò)以上操作,五個(gè)表之間的連接成功建立,便可以對(duì)這些表進(jìn)行復(fù)雜的數(shù)據(jù)處理和查詢。