使用内部联接中的select count()更新mysql

时间:2016-07-13 14:01:00

标签: mysql sql-update inner-join

我有以下select语句,它计算值在连接表中出现的次数:

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

现在我想用这些结果更新第三个表,设置table3.idx = table1.idx的计数。我试过了

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;

根据modulo function的建议,并尝试了

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

How do I UPDATE from a SELECT in SQL Server?中的建议,但它们都不起作用。什么是正确的语法?

1 个答案:

答案 0 :(得分: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