简体   繁体   English

如何同时更新和选择

[英]How UPDATE and SELECT at the same time

I need to update some rows of the tables and then display these rows. 我需要更新表的某些行,然后显示这些行。 Is there a way to do this with one single query and avoid this 2 query ? 有一种方法可以通过一个查询来执行此操作,而避免执行这两个查询吗? :

UPDATE table SET foo=1 WHERE boo=2

SELECT * from table WHERE ( foo=1 ) AND ( boo=2 )

In PostgreSQL v8.2 and newer you can do this using RETURNING : 在PostgreSQL v8.2及更高版本中,您可以使用RETURNING进行此操作:

UPDATE table
SET foo=1
WHERE boo=2
RETURNING *

You can use a stored procedure in PL/pgSQL. 您可以在PL / pgSQL中使用存储过程。 Take a look at the [docs][1] 看看[docs] [1]

Something like this 像这样

CREATE FUNCTION run(fooVal int, booVal int) 
RETURNS TABLE(fooVal int, booVal int)
AS $$
BEGIN
  UPDATE table SET foo = fooVal WHERE boo= booVal;
  RETURN QUERY SELECT fooVal, booVal from table WHERE ( foo = fooVal ) AND ( boo = booVal );
END;
$$ LANGUAGE plpgsql;

You will save the roundtrip time for sending another statement. 您将节省发送另一条语句的往返时间。 This should not be a performance bottleneck. 这不应该是性能瓶颈。 So short answer: Just use two queries. 答案很简短:只需使用两个查询。 That's fine and this is how you do it in SQL. 很好,这就是您在SQL中的操作方式。

[1]: http://www.postgresql.org/docs/8.4/static/plpgsql.html docs [1]: http//www.postgresql.org/docs/8.4/static/plpgsql.html docs

You can use stored procedure or function. 您可以使用存储过程或函数。 It will contains your queries. 它将包含您的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM