2012-08-05 19 views
1

我目前使用下面的查詢,以確定哪些項目在數據庫中有沒有相關的里程碑:使用輸出作爲條件查詢乙

SELECT P.project_id, COUNT(M.milestone_id) as count FROM projects P 
LEFT JOIN milestones M USING(project_id) 
GROUP BY P.project_id 
HAVING count < 1 

,並返回:

project count 
--------------- 
9   0 
34  0 
32  0 
41  0 

我現在該如何去INSERT這個表中每個project_id的新里程碑行?

回答

3

要插入新行/秒,您可以使用INSERT...SELECT聲明

INSERT INTO tableName (project_ID) 
SELECT P.project_id 
FROM projects P 
      LEFT JOIN milestones M 
       USING(project_id) 
GROUP BY P.project_id 
HAVING count < 1 

變化tableNAme表的名稱。

更新1

INSERT INTO tableName (project_ID, colA, colB, colC) 
SELECT P.project_id, colA, colB, colC 
FROM projects P 
      LEFT JOIN milestones M 
       USING(project_id) 
GROUP BY P.project_id 
HAVING count < 1 

現在問題出現了,如果你想有一個值中不存在該列是什麼?您可以爲此創建虛擬值。

INSERT INTO tableName (project_ID, field1, field2, field3) 
SELECT P.project_id, '' AS field1, 0 AS field2, NULL AS field3 
FROM projects P 
      LEFT JOIN milestones M 
       USING(project_id) 
GROUP BY P.project_id 
HAVING count < 1 
+0

真棒。如果我想給它更多的值只是項目ID? – Kristian 2012-08-05 14:26:44

+0

您只需在INSERT語句INSERT INTO tableName(project_ID,field_1,field_2,...,field_N)中添加字段名稱,然後尋址SELECT語句部分中的相應列。 – wisefish 2012-08-05 14:30:42

+0

您可以爲此添加更多行。順便說一句,我剛剛更新了答案。 – 2012-08-05 14:31:04