使用MySQL服务器中同一表中其他列的计数更新表的列

时间:2014-05-11 16:42:25

标签: mysql

我有一张这样的表:

recordid customerid产品ID计数
1 2 12 3
   2 4 10 1
   3 2 3 3
   4 3 12 2
   5 3 10 2
   6 2 7 3
   7 5 3 1
   8 ....    9 ....

我想要一个更新查询,它会计算每个客户ID的出现次数,并更新最初为空的count列。 最终结果应如上所述 列名是虚拟的,我的实际表是不同的。 它有数百万行的数据。查询应该很快 我尝试了查询,但它被卡住了...... update tablename,(select count(recordid)as count,customerid from tablename group by customerid)as temp set count = temp.count where customerid = temp.customerid

2 个答案:

答案 0 :(得分:2)

您可以在JOIN中使用UPDATE

试试这个:

UPDATE TableName A
JOIN 
(SELECT customerid,Count(customerid) as cnt
FROM TableName
GROUP BY customerid) as B ON A.customerid= B.customerid
SET A.count = B.cnt

答案 1 :(得分:0)

这看不对:

update tablename, (select count(recordid) as count,customerid from tablename group by customerid) as temp set count=temp.count where customerid=temp.customerid

为什么update tablename之后会出现逗号:

update tablename, 

我也在重新格式化以提高可读性:

UPDATE tablename (
  SELECT count(recordid) AS count, customerid
  FROM tablename GROUP BY customerid
) as temp
SET count=temp.count
WHERE customerid = temp.customerid