2013-12-17 69 views
1

我一直在努力尋找MySQL更新查詢一段時間,但找不到解決方案。MySql將選擇查詢轉換爲更新

Table_Items: 
- id 
- desc 
- maintenance_times 

Table_Maintenances: 
- id 
- Item_id 
- maintenance_desc 

它們與對方喜歡

Table_Items.id=Table_Maintenances.Item_id 

現在我想從表Table_Maintenances計數的維護數量爲每個項目和更新欄maintenace_time in Table_Items

我有工作的選擇查詢,但無法弄清楚如何在Table_items更新每一行(maintenance_times):

SELECT COUNT(b.Item_id) 
FROM `Table_Items` AS a 
LEFT JOIN Table_maintenances as B ON a.id=b.Item_id 
GROUP BY b.Item_id 
+1

HTTP ://stackoverflow.com/questions/4268416/sql-update-with-sub-query-that-references-the-same-table-in-mysql –

回答

2

想通了最後感謝您的例子:

UPDATE 
    Table_Items m, 
    (
    SELECT a.id, COUNT(b.Item_id) cnt 
    FROM `Table_Items` AS a 
    LEFT JOIN Table_Maintenances as B on a.id=b.Item_id 
    GROUP BY b.Item_id 
) q 
SET m.maintenance_times = q.cnt 
WHERE m.id = q.id