有三張 table
table host 有 id, hostname
table grp 有 id, grp_name
table grp_host 有 grp_id, host_id => 這張表用來記錄 grp 和 host 之間的 relation
需求是:要寫入 grp_host 這張表,但是,原始資料的 grp 與 host 的 relation ,是用字串來記錄的,也就是 (string, string) 這樣子的 tuple。
總之,這個寫入的合理作法,要用一點小技巧:
建立 temporary table,然後 insert into ... select ,還有,要包在一個 transaction 裡頭!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DROP TEMPORARY TABLE IF EXISTS trel; | |
CREATE TEMPORARY TABLE trel ( | |
grp_name varchar(255) NOT NULL DEFAULT '', | |
hostname varchar(255) NOT NULL DEFAULT '' | |
) ENGINE=MEMORY DEFAULT CHARSET=utf8; | |
INSERT INTO trel(grp_name, hostname) VALUES (:gname, :hname) ... ; | |
INSERT INTO grp_host (grp_id, host_id) | |
SELECT grp.id, host.id FROM grp, trel, host | |
WHERE grp.grp_name = trel.grp_name | |
AND host.hostname = trel.hostname; | |
DROP TEMPORARY TABLE trel; |