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....)
UPDATE e a, (SELECT e1,COUNT(*) cnt
FROM e
GROUP BY e1) b
SET a.e2 = b.cnt
WHERE a.e1 = b.e1;
with
AAA AS
(
select e1,count(*) as cnt from e group by e1
)
update e
set e2 = AAA.cnt
from e
inner join AAA ON e.e1 = AAA.e1
Try Following Query :
update e
set e2 = a.cnt
from e inner join (select e1,count(*) as cnt from e as a group by e1) as a ON e.e1 = A.e1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.