2013-08-03 51 views
4

我的表方案如下存在:(粗體列名是主鍵)從一個表中選擇數據,並插入到另一個現有的表,其不表中

表1:ID1 - ID2

表2:ID2 - NAME2

表3:ID3 - NAME3

表4:ID1 - ID3

我想要做的是有SQL代碼:

  1. 在ID1和ID3列選擇數據,其名稱2 =輸入= NAME3
  2. 插入到表4
  3. 只有插入4如果ID1,ID3組合不表4

目前我能做的步驟1和2,但(假設是可以做到的),我不能得到的語法「不存在」的步驟3

正確的存在

這是目前我的代碼:

INSERT INTO table4(id1, id3) 
SELECT id1, id3 
FROM table2 
INNER JOIN table1 ON table1.id2 = table2.id2 
INNER JOIN table3 ON table2.name2 = table3.name3 
WHERE name2 LIKE 'input' 

回答

1

這裏查詢你需要

insert into table4(id1, id3) 
select t1.id1, t3.id3 
from table2 as t2 
    inner join table1 as t1 on t1.id2 = t2.id2 
    inner join table3 as t2 on t2.name2 = t3.name3 
where 
    t2.name2 like 'input' and 
    not exists (
     select * 
     from table4 as t4 
     where t4.id1 = t1.id1 and t4.id3 = t3.id3 
    ) 

作爲一個建議 - 我建議你總是在查詢中使用別名(並參考列alias.column_name),它會幫助你避免錯誤和您的查詢將更具可讀性。

+0

感謝這工作,我不知道別名 – Menlo123

0

我認爲你正在尋找這個

INSERT INTO table4(id1, id3) 
SELECT id1, id3 
FROM table2 
INNER JOIN table1 ON table1.id2 = table2.id2 
Left JOIN table3 ON table2.name2 = table3.name3 
WHERE name2 LIKE 'input' and table3.name3 is null 

或類似的東西。左(外連接)獲取table2中的所有記錄,無論它們是否存在。如果他們不table3.name3將是空的,所以那些是你想要的chaps。

0

您當前的查詢可以插入, 但是如果您想要拒絕插入,如果該組合已存在, 只需向包含這2列的表4添加主鍵。

在查詢做:

INSERT INTO table4(id1, id3) 
SELECT id1, id3 
FROM table2 
INNER JOIN table1 ON table1.id2 = table2.id2 
INNER JOIN table3 ON table2.name2 = table3.name3 
WHERE name2 LIKE 'input' 
ON DUPLICATE KEY UPDATE id1=id1; 

,這只是爲了使查詢仍然可以運行, 如果有重複它不會做任何事情。

相關問題