0

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. I am struggling to insert data that is partially provided by a php call and partially provided by a select statement. 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.

3
  • 2
    try $query = "INSERT INTO deals (latitude, longitude, interested, id, the_geom) VALUES SELECT $1, $2, $3, $4, the_geom FROM userlocs WHERE id=$3"; Commented Jan 27, 2015 at 1:58
  • @Sean thanks for the suggestion, but this is giving me the same "syntax error" message. Commented Jan 27, 2015 at 2:04
  • it looks like postgresql does not use the VALUES when doing INSERT ... SELECT, so try $query = "INSERT INTO deals (latitude, longitude, interested, id, the_geom) SELECT $1, $2, $3, $4, the_geom FROM userlocs WHERE id=$3"; Commented Jan 27, 2015 at 2:08

1 Answer 1

1

Probably the easiest fix is to just put your SELECT statement in parentheses

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

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

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) 
Sign up to request clarification or add additional context in comments.

5 Comments

maybe max(the_geom) helping.
@ColourDalnet For what possible reason one would want to use an aggregate in this case?
if have more than 1 results.
@ColourDalnet Fair enough. But it only make sense if id for some reason is not the PK. A better alternative in that situation might be to use LIMIT 1.
Yes, that is just the case id is not primary key, for example many-to-many relationship table. LIMIT 1 is better combined with ORDER BY :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.