简体   繁体   English

PostgreSQL中的insert…select语句将php中的插入值与select语句组合在一起

[英]insert…select statement in postgresql combining inserted values from php with a select statement

I have seen some SO posts on how to insert selected values, but they are always in cases where all inserted values will come from the select statement. 我已经看到了一些关于如何插入所选值的SO帖子,但是在所有插入的值都将来自select语句的情况下,它们总是存在的。 I am struggling to insert data that is partially provided by a php call and partially provided by a select statement. 我正在努力插入部分由php调用提供的数据和部分由select语句提供的数据。 Here is what I would like to do: 这是我想做的:

$query = "INSERT INTO deals (latitude, longitude, interested, id, the_geom) VALUES ($1, $2, $3, $4, SELECT the_geom FROM userlocs WHERE id=$3)";
$rs = pg_query_params($con, $query, array($latitudeS, $longitudeS, $id_pg , $id_add));

This is giving me the following not very helpful error: 这给了我以下不是很有帮助的错误:

 pg_query_params(): Query failed: ERROR: syntax error at or near "SELECT" LINE 1: ...interested, id, the_geom) VALUES ($1, $2, $3, $4, SELECT the... ^ in /var/www/html/join.php on line 30

Is it possible to do what I would like to do? 有可能做我想做的事吗? If so, how do I modify my syntax? 如果是这样,如何修改语法?

Many thanks for any suggestions. 非常感谢您的任何建议。

Probably the easiest fix is to just put your SELECT statement in parentheses 可能最简单的解决方法是将SELECT语句放在括号中

INSERT INTO deals (latitude, longitude, interested, id, the_geom) 
VALUES ($1, $2, $3, $4, (SELECT the_geom FROM userlocs WHERE id = $3))

Here is a SQLFiddle demo 这是一个SQLFiddle演示

Depending on whether you always expect a value coming from userlocs or not you can also use INSERT ... SELECT syntax in one of two ways 根据您是否始终期望来自userlocs的值,还可以通过以下两种方式之一使用INSERT ... SELECT语法

INSERT INTO deals (latitude, longitude, interested, id, the_geom) 
SELECT $1, $2, $3, $4, the_geom FROM userlocs WHERE id = $3

or 要么

INSERT INTO deals (latitude, longitude, interested, id, the_geom) 
SELECT $1, $2, $3, $4, (SELECT the_geom FROM userlocs WHERE id = $3) 

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

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