PostgreSQL:使用同一表上的 select 语句更新字段

发布于 2024-10-18 13:05:56 字数 456 浏览 2 评论 0原文

我需要更新随机选择的样本表中的字段。 如果我运行此查询,它将正确返回所选的 57 行:

SELECT * FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' ORDER BY random() LIMIT (57)

我现在要做的是应用该 SELCT 语句来用“YY”更新 item1,但仅限于随机选择的 57 行。 我尝试这样做:

UPDATE table
SET item1 = 'YY'
WHERE id_item = (SELECT id_item FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' 
ORDER BY random() LIMIT (57))

但它返回错误:“用作表达式的子查询返回的不止一行”。

如何更新表中的随机行数? 提前致谢

I need to update a field in a table on a sample randomly selected.
If I run this query it returns correctly the selected 57 rows:

SELECT * FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' ORDER BY random() LIMIT (57)

What I want to do now is to apply that SELCT statement to UPDATE the item1 with 'YY', but only for the 57 randomly selected rows.
I try this:

UPDATE table
SET item1 = 'YY'
WHERE id_item = (SELECT id_item FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' 
ORDER BY random() LIMIT (57))

but it returns the error: "more than one row returned by a subquery used as an expression".

How can I update a table for a random number of rows?
Thanks in advance

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

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

发布评论

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

评论(3

心安伴我暖 2024-10-25 13:05:56

将“=”运算符更改为 IN。

UPDATE table
SET item1 = 'YY'
WHERE id_item IN (SELECT id_item 
                  FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' 
                  ORDER BY random() LIMIT (57))

Change the "=" operator to be IN instead.

UPDATE table
SET item1 = 'YY'
WHERE id_item IN (SELECT id_item 
                  FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' 
                  ORDER BY random() LIMIT (57))
傲影 2024-10-25 13:05:56

Chage = “在”。

您需要将其更改为:

UPDATE table SET item1 = 'YY' WHERE id_item in (SELECT id_item FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' ORDER BY random() LIMIT (57))

Chage = to "in".

You need to change it to this:

UPDATE table SET item1 = 'YY' WHERE id_item in (SELECT id_item FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' ORDER BY random() LIMIT (57))
冬天旳寂寞 2024-10-25 13:05:56

对于 WHERE 子句,您可能需要使用 IN 运算符而不是 =。

UPDATE table
SET item1 = 'YY'
WHERE id_item IN (SELECT id_item FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' 
ORDER BY random() LIMIT (57))**

You may need to use IN operator instead of = for WHERE clause.

UPDATE table
SET item1 = 'YY'
WHERE id_item IN (SELECT id_item FROM table WHERE item1 = 'XX' AND item2 = 'JJJ' 
ORDER BY random() LIMIT (57))**
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文