2012-06-14 30 views
0

我得到了這個已經工作;調整插入到SQL

INSERT INTO TermsFinal 
      (old_classification, count, new_classification, old_term,new_term) 
     SELECT old_classification , Count(seed) AS count , new_classification, old_term, new_term FROM TermsTemp 
      GROUP BY old_classification 
      ORDER BY count DESC  

TermsTemp並沒有一個字段名爲SOURCE_TABLE,它被稱爲SOURCE_TABLE。 我也想填充該字段。我已經獲得了$ source_table值。我嘗試過,但沒有工作。

INSERT INTO TermsFinal 
      (SOURCE_TABLE,old_classification, count, new_classification, old_term,new_term) 
    '{$SOURCE_TABLE}', SELECT old_classification , Count(seed) AS count , new_classification, old_term, new_term FROM TermsTemp_TEMP 
      GROUP BY old_classification 
      ORDER BY count DESC 

如何在執行insert into語句時將該值添加到TermsFinal的SOURCE_TABLE字段中?

和另一個讓我困惑的事情在這裏,我的第一個SQL insertinto如何在沒有SQL關鍵字VALUES的情況下工作。此頁http://www.w3schools.com/sql/sql_insert.asp教導VALUES部分是必要的!

回答

2

您可以將字符串(或任何其他類型)常量放入select中,例如 select 'string' as const_str , field1 from table1將返回2列,第一列將具有所有行的「字符串」文本。你的情況,你可以做

INSERT INTO TermsFinal 
     (SOURCE_TABLE,old_classification, count, new_classification, old_term,new_term) 
    SELECT '{$SOURCE_TABLE}', old_classification , Count(seed) AS count , new_classification, old_term, new_term FROM TermsTemp_TEMP 
     GROUP BY old_classification 
     ORDER BY count DESC 
1

有幾種方法同時將數據插入到表

一行。這是你需要values關鍵字的地方。

Insert into TableA (Col1, Col2,...) values (@Val1, @Val2,...) 

您可以使用select @@身份(至少在MS SQL)獲得ID,如果您有自動身份 。當你需要下一個插入的ID時,這很有用。

選擇從(你在做什麼)

Insert into tableA (Col1, Col2) 
Select Val1, Val2 from TableB 

或插入來自兩個獨立的表

Insert into tableA (Col1, Col2, Col3, Col4) 
Select 'hard coded value', b.Val1, b.Val2, c.Val1 
from TableB b join Table c on b.TableCID=c.ID 

現在硬編碼值和值,您可以在插入多行一旦。

選擇到

這種方法最終從查詢創建新表,是偉大的表的快速備份,或表的一部分。

select * into TermsFinal_backup from TermsFinal where ...