将列值更新为同一表中特定值的 COUNT 行 [英] Update a column value to the COUNT of rows for specific values in same table

查看:51
本文介绍了将列值更新为同一表中特定值的 COUNT 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数据从 MySQL 导出到 .csv,我需要在其中包含基于表中特定列的行数.

I am working on an export of data from MySQL to .csv where I need to include a row count based on a specific column in the table.

我有一个名为 e 的表,其中包含 ide1e2

I have a table called e with the columns id, e1 and e2

|id|e1|e2|
| 1| A|  |
| 2| A|  |
| 3| A|  |
| 4| B|  |
| 5| C|  |
| 6| B|  |

我正在寻找的结果是:

|id|e1|e2|
| 1| A| 3|
| 2| A| 3|
| 3| A| 3|
| 4| B| 2|
| 5| C| 1|
| 6| B| 2|

如果我尝试这样的事情:

If I try something like this:

UPDATE `e` SET `e2` = (SELECT COUNT(`id`) FROM `e` WHERE `e1` = 'A') WHERE `e1` = 'A';

我得到:您不能在 FROM 子句中指定更新目标表e"

如何更新我的数据,以便 e2 中的值是具有 e1 值的行的 COUNT?这是我不能/不应该在 MySQL 中做但应该在 PHP 中做的事情吗?

How can I go about updating my data so that the value in e2 is the COUNT of the rows with the value from e1? Is this something I can't/shouldn't do in MySQL but should be doing in PHP?

(我觉得我错过了一些明显的东西......)

(I feel like I'm missing something obvious....)

推荐答案

UPDATE e a, (SELECT e1,COUNT(*) cnt 
               FROM e 
           GROUP BY e1) b

   SET a.e2 = b.cnt
 WHERE a.e1 = b.e1;

这篇关于将列值更新为同一表中特定值的 COUNT 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆