在mysql的更新中执行count()?

发布于 2024-11-15 13:50:51 字数 349 浏览 1 评论 0原文

是否可以进行如下查询?如果可能的话,我想用这个来代替存储过程。

例如,有两个表

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

或类似的东西...本质上是对一个表进行计数并使用该值来更新另一个表?

我什至不知道这个问题是否有意义。如果需要的话,请随意称我为白痴。

编辑抱歉,这个问题可能没有意义。我想对表“B”进行计数并使用该值在同一查询中更新表“A”。

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
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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧城烟雨 2024-11-22 13:50:51

当然,您的语法基本上是正确的:

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

这称为相关子查询。它是相关的,因为您在子查询中引用了外部查询中的表。

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.

风蛊 2024-11-22 13:50:51

您正在寻找的是 mysql_affected_rows() ,查询后可以立即调用,查看更新了多少条记录。

你其实已经很接近了!怎么样:

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

编辑:Rafe 首先发布了他的解决方案。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文