0

I have the following select statement that counts the number of times a value appears in a joined table:

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

Now I want to update a third table with these results, setting the counts where table3.idx = table1.idx. I've tried

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;

as recommended at How do I UPDATE from a SELECT in SQL Server?, and also tried

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);

as recommended in MySQL - UPDATE query based on SELECT Query, but neither of them work. What's the correct syntax?

Community
  • 1
  • 1
user2667066
  • 1,867
  • 2
  • 19
  • 30

1 Answers1

2
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
juergen d
  • 201,996
  • 37
  • 293
  • 362