Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 您可以一起运行更新和吗?_Sql_Postgresql - Fatal编程技术网

Sql 您可以一起运行更新和吗?

Sql 您可以一起运行更新和吗?,sql,postgresql,Sql,Postgresql,我试图在表上运行更新,但出现错误 ERROR: syntax error at or near "UPDATE" 查询是: WITH first_users AS ( select min(created_at) as first_at, company_id as company_id from users group by company_id ) UPDATE companies SET first_seen_at = LEAST(first

我试图在表上运行更新,但出现错误

ERROR:  syntax error at or near "UPDATE"
查询是:

WITH
  first_users AS (
    select min(created_at) as first_at,
    company_id as company_id
    from users
    group by company_id
  )

UPDATE companies
 SET first_seen_at = LEAST(first_seen_at,
    (SELECT first_at FROM first_users WHERE id = first_users.company_id)
 );
您不能同时运行更新和吗?看起来很奇怪


我的查询实际上稍微复杂一些,这就是为什么我使用with语法的原因。当我从first_users运行SELECT*而不是UPDATE时,它会工作,因此UPDATE关键字或其他东西有问题。

我建议将其更改为UPDATE。不管怎么说,都是我的。没有理由更新不匹配的记录。因此:

update companies
   set first_seen_at = u.first_at
   from (select company_id, min(created_at) as first_at
         from users
         group by company_id
        ) u
   where companies.id = u.company_id and
         u.first_seen_at < companies.first_seen_at;

Postgres开始支持CTE,并在9.1版vs中进行了更新。此方法更好,因为它在更新之前过滤行。

尝试封装查询qith BEGIN/END。我不知道PostgreSql,但是MsSql不接受没有开始/结束的…

Postgres肯定支持使用for update。从9.1版开始。旧版本不支持此功能。是否可以加入公司和first_用户,并在何时执行案例?更新c SET c.first_seen_at=case when c.first_seen_at>u.first_at然后u.first_at ELSE c.first_seen_END FROM first_users u internal join companys c ON u.company_id=c.idEdit您的问题,并粘贴CREATETABLE和INSERT语句。请使用实际表格的结构。我根据UPDATE语句猜测了您的表结构,没有语法错误。@MikeSherrill'CatRecall'。你有SQL Fiddle上的表吗?没有,我已经很久没有使用SQL Fiddle了。b我没有在你的update语句中发现语法错误;我有运行时错误。我没有保留这些表,但我可能使用了类似于create table users created_at timestamp,company_id integer的东西;创建表COMPANYS id integer,在时间戳处第一次看到;“我实在太困了,不能上StackOverflow了。”@MikeSherrill'CatRecall'。出现两个错误,因为在子查询中选择了两次company_id,并且更新时字段名错误。错误:关系u不存在exist@Jeff . . . u是在from子句中定义的,所以我不明白为什么它不能被识别。