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.
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| |
The result I'm looking for is:
|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';
I get: You can't specify target table 'e' for update in FROM clause
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....)