开发者

Doing a count() in an update in mysql?

开发者 https://www.devze.com 2023-03-13 17:26 出处:网络
Is it possible to do a query like the following? I would like to do this in place of a stored procedure if possible.

Is it possible to do a query like the following? I would like to do this in place of a stored procedure if possible.

for example, with two tables

UPDATE items
开发者_Python百科SET score='a', count=(SELECT COUNT(votes.id) AS C WHERE votes.uri = items.uri)
WHERE items.id = 'b'

Or something like that... Essentially doing a count on a table and using that value to update another table?

I don't even know if this question makes sense. Feel free to call me a moron if need be.

Edit sorry, this question might not make sense. I want to count table "B" and use that value to update table "A" in the same query.


Sure, you've got the syntax basically right:

UPDATE items
SET score= 'a', count = (SELECT COUNT(votes.id)
    FROM votes WHERE votes.uri = items.uri)
WHERE items.id = 'b'

This is called a correlated subquery. It's correlated because you refer to the table in the outer query in the subquery.


What you're looking for is mysql_affected_rows(), you can call it immediately after the query to see how many records were updated.

You are actually very close! How about this:

UPDATE items SET score='a', count = (SELECT COUNT(votes.id) FROM votes WHERE votes.uri = items.uri) WHERE items.id = 'b'

edit: Rafe posted his solution first.

0

精彩评论

暂无评论...
验证码 换一张
取 消