【问题标题】:Updating a table in PostgreSQL query在 PostgreSQL 查询中更新表
【发布时间】:2021-12-20 04:52:59
【问题描述】:

我有以下,价格后面的尾随空格是故意的:

UPDATE table1
SET "Price " = table2."Price"
FROM table2
WHERE table2."ATT2" = table1."ATT2"

这成功返回:

更新 14

但是,当我执行时

SELECT * FROM table1;

table1 没有按照应有的方式更新 table2 的价格。

完整代码:

UPDATE table1
SET "Price " = table2."Price"
FROM table2
WHERE table2."ATT2" = table1."ATT2";
SELECT * FROM table1;

使用 pgAdmin4,在 psql 客户端中也尝试过,但没有运气。我宁愿使用 pdAdmin4。

此问题尚未解决,因此非常感谢任何帮助

【问题讨论】:

  • 可能找不到匹配的行。它对我有用。
  • 我使用以下命令检查是否有匹配的行:``` SELECT count(*) FROM table1, table2 WHERE table2."ATT2" = table1."ATT2";``` 这将返回 14 ,解释了为什么上面的问题查询返回 UPDATE 14。但是 table1 仍然没有用 table2 价格更新。
  • 您的某一列的名称中是否真的有尾随空格?
  • A) 你怎么知道它成功更新了? B) "Price " 的末尾应该有一个空格吗? C) 您是否在交易中执行此操作而忘记了COMMIT?添加答案以更新您的问题。
  • @jjanes 是的,有一个培训空间,这不应该改变导致我的解决方案失败。

标签: sql postgresql sql-update


【解决方案1】:

这可能是您的查询中的拼写错误:

UPDATE table1
SET "Price " = table2."Price" -- price has one extra space at the end
FROM table2
WHERE table2."ATT2" = table1."ATT2"

【讨论】:

  • 需要额外的空间,这不是问题的原因
【解决方案2】:

也许你可以使用类似的东西:

UPDATE table1
SET "Price " = (
   select table2."Price" 
   FROM table2
   WHERE table2."ATT2" = table1."ATT2")

我用这个表/更新做了一些测试:

create table scientist1 (id integer, firstname varchar(100), lastname varchar(100));
        insert into scientist1 (id, firstname, lastname) values (1, 'albert 1', 'einstein');
        insert into scientist1 (id, firstname, lastname) values (2, 'isaac 1', 'newton');
        insert into scientist1 (id, firstname, lastname) values (3, 'marie 1', 'curie');

create table scientist2 (id integer, firstname varchar(100), lastname varchar(100));
        insert into scientist2 (id, firstname, lastname) values (1, 'albert 2', 'einstein');
        insert into scientist2 (id, firstname, lastname) values (2, 'isaac 2', 'newton');
        insert into scientist2 (id, firstname, lastname) values (3, 'marie 2', 'curie');

        
        
UPDATE scientist1
SET firstname = (select scientist2.firstname FROM scientist2
                 WHERE scientist2.id = scientist1.id);

【讨论】:

    猜你喜欢
    • 2015-10-28
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2023-04-08
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多