mysql 计数更新,Mysql:使用来自同一表的计数更新表

I have a table like:

`url` varchar(255) NOT NULL,

`cnturl` int(11) DEFAULT NULL,

'url' contains some urls. In 'cnturl' I want to store how many times the same url is inside the table (yes, it's redundant, I'm doing this for speed reasons).

So to update these values I need something like:

UPDATE urltable

SET cnturl=(

SELECT COUNT(t.id) FROM urltable AS t WHERE t.url=urltable.url

);

But this gives me the error:

You can't specify target table 'urltable ' for update in FROM clause

I tried as well:

UPDATE urltable

INNER JOIN (

SELECT COUNT(*) as cnt, url FROM urltable

) t

ON t.url=urltable.url

SET urltable.cnturl = t.cnt;

But this gives just wrong results (some counts are NULL while others are the count of all records).

I tried as well:

UPDATE urltable SET cnturl =

(SELECT t.cnt FROM

(SELECT COUNT(t.id) AS cnt, url FROM urltable) t

WHERE t.url=urltable.url)

But this gives the same wrong results (some counts are NULL while others are the count of all records).

I guess it should be more something like this:

UPDATE urltable

INNER JOIN (

SELECT COUNT(*) as cnt, url FROM urltable t

WHERE t.url=urltable.url;

) t

SET urltable.cnturl = t.cnt;

But this ends up with: Unknown column 'urltable.url' in 'where clause'.

I couldn't find any other solutions for this. Any other ideas?

解决方案

Try this one:

UPDATE urltable

INNER JOIN (

SELECT IFNULL(COUNT(url),0) as cnt, url FROM urltable

GROUP BY url

) t

ON t.url=urltable.url

SET urltable.cnturl = t.cnt;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值