MySQL计算另一列中列的值出现次数并存储在新列中

时间:2016-04-05 12:58:01

标签: mysql

如何构建查询以便计算第1列中出现的值的次数,然后将该结果存储在同一个表中的新列中? (如果第一列中的值重复,我仍然希望在新列中存储相同的值)例如,如果我有一个这样的表:

COL1    COL2
1        2
1        4
2        1
3        1
4        1
4        2

结果表格如下所示:

COL1    COL2    COL3
1        2       3
1        4       3
2        1       2
3        1       0
4        1       1
4        2       1

感谢任何帮助我是sql的新手!提前谢谢!

3 个答案:

答案 0 :(得分:1)

您可以轻松地实时计算。不要冗余地存储它。这只会在以后引起问题。

select 
  col1, 
  col2,
  (
    select count(*)
    from mytable match
    where match.col2 = mytable.col1
  ) as col3
from mytable;

如果您认为必须这样做;这是相应的UPDATE声明:

update mytable 
set col3 =
(
  select count(*)
  from mytable match
  where match.col2 = mytable.col1
);

答案 1 :(得分:0)

为此,您可以尝试:

SELECT COL1, COL2, (SELECT COUNT(COL1) FROM `tablename` AS t2 
WHERE t2.COL1 = t1.COL1) AS COL3 FROM `tablename` AS t1

享受:)

答案 2 :(得分:0)

Select 
 col1,
 col2,
 COALESCE(col3,0) as col3
FROM 
 mytable 
LEFT JOIN 
( Select count(*) as col3, col2
    from mytable 
   GROUP BY col2) as temp ON temp.col2 = mytable.col1

如果你想要更新(感谢Thorsten Kettner):

UPDATE mytable 
LEFT JOIN ( Select count(*) as col3, col2
    from mytable 
   GROUP BY col2) as temp ON temp.col2 = mytable.col1
SET mytable.col3 =  COALESCE(temp.col3,0)