2016-07-13 12 views
0

Ich habe folgende select-Anweisung, die die Anzahl von Malen ein Wert in einer verknüpften Tabelle erscheint zählt:mysql-Update mit select count() von INNER JOIN

SELECT table1.idx, count(table1.idx) FROM 
(table2 INNER JOIN table1 ON table1.id=table2.id AND table2.value = 'target') 
GROUP BY table1.idx; 

Jetzt möchte ich mit diesen eine dritte Tabelle aktualisieren, results, die counts setzen wo table3.idx = table1.idx. Ich habe versucht,

UPDATE table3 SET count_col=joined_table.c FROM 
(SELECT table1.idx, count(table1.idx) FROM 
    (table2 INNER JOIN table1 ON table1.id=table2.id AND table2.value = 'target') 
    GROUP BY table1.idx 
) joined_table WHERE table3.idx = table1.idx; 

wie bei How do I UPDATE from a SELECT in SQL Server? empfohlen, und auch versucht,

UPDATE table3 SET count_col=(
    SELECT COUNT(table1.idx) 
    FROM (table1 INNER JOIN table2 ON table1.id=table2.id AND table2.value = 'target') 
    GROUP BY table1.idx 
WHERE table3.idx = table1.idx); 

wie in MySQL - UPDATE query based on SELECT Query empfohlen, aber keiner von ihnen arbeiten. Was ist die korrekte Syntax?

Antwort

1
UPDATE table3 
JOIN 
(
    SELECT table1.idx, count(table1.idx) as cnt 
    FROM table2 
    INNER JOIN table1 ON table1.id = table2.id 
        AND table2.value = 'target' 
    GROUP BY table1.idx 
) joined_table ON table3.idx = joined_table.idx 
SET count_col = joined_table.cnt 
+0

Perfekt. *Vielen Dank* – user2667066