一、使用場(chǎng)景
我們使用MYSQL的時(shí)候,為了防止重復(fù)的插入胀瞪,我們就需要先判斷是否數(shù)據(jù)庫(kù)中時(shí)候存在相同的記錄。MySQL我們借助于insert into select from的語(yǔ)法進(jìn)行處理這種問(wèn)題饲鄙。
二凄诞、示例
1、單條插入:通過(guò)dual偽表來(lái)判斷傍妒。
INSERT INTO clients
(client_id, client_name,)
SELECT 1, 'Calvin',
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 1);
JDBC插入語(yǔ)句示例
INSERT INTO tbl_teahouse_member
(player_id,house_id ,status)
SELECT ?,? ,? FROM dual
WHERE not exists (select * from tbl_teahouse_member
WHERE house_id = ? and player_id= ? )
2幔摸、多條插入:通過(guò)關(guān)聯(lián)表
INSERT INTO clients
(client_id, client_name)
SELECT supplier_id, supplier_name
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);