基于条件的同一表的计数mySQL更新

发布于 2025-02-13 08:18:51 字数 625 浏览 1 评论 0原文

我需要根据两个条件更新类别表:

  1. 类别必须为top
  2. 该类别必须至少具有5个儿童类别。

以下查询:

UPDATE categories AS c
SET c.columns = 4
WHERE c.top = 1 AND (SELECT COUNT(*) FROM categories WHERE parent_id = c.id) >= 5

返回错误:

#1093-表'C'指定了两次,既是“更新”的目标,也是数据的单独来源

我知道我需要在表上应用不同的别名,因此我尝试了:

UPDATE categories AS c
SET c.columns = 4
WHERE c.top = 1 AND (SELECT COUNT(*) FROM (SELECT * FROM categories WHERE parent_id = c.id) AS c2) >= 5

但是这返回了另一个错误:

#1054-未知列'c.id'in where子句'

I need to update the categories table based on two conditions:

  1. The category must be top
  2. The category must have at least 5 child categories

The following query:

UPDATE categories AS c
SET c.columns = 4
WHERE c.top = 1 AND (SELECT COUNT(*) FROM categories WHERE parent_id = c.id) >= 5

Returns the error:

#1093 - Table 'c' is specified twice, both as a target for 'UPDATE' and as a separate source for data

I understand that I need to apply a different alias to the table, therefore I tried:

UPDATE categories AS c
SET c.columns = 4
WHERE c.top = 1 AND (SELECT COUNT(*) FROM (SELECT * FROM categories WHERE parent_id = c.id) AS c2) >= 5

But this returns another error:

#1054 - Unknown column 'c.id' in 'where clause'

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

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

发布评论

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

评论(1

不顾 2025-02-20 08:18:51

将表加入至少5个儿童类别的类别的查询:

UPDATE categories AS c
INNER JOIN (
  SELECT parent_id
  FROM categories 
  GROUP BY parent_id
  HAVING COUNT(*) > 5
) AS t ON t.parent_id = c.id
SET c.columns = 4
WHERE c.top = 1;

Join the table to a query that returns the categories with at least 5 child categories:

UPDATE categories AS c
INNER JOIN (
  SELECT parent_id
  FROM categories 
  GROUP BY parent_id
  HAVING COUNT(*) > 5
) AS t ON t.parent_id = c.id
SET c.columns = 4
WHERE c.top = 1;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文