Quantcast
Channel: Question and Answer » postgresql
Viewing all articles
Browse latest Browse all 1138

Combining 2 SELECT queries and printing the results in PostgreSQL

$
0
0

I have 2 queries which I want to use together to produce one output result to the user. The output describes to the user the journey to take to from A to B. I keep getting a syntax error when I try to combine both queries with UNION:

Query failed: ERROR: syntax error at or near "UNION" LINE 6: UNION ^

I have had a look at a similar question but the solutions & discussions provided do not seem to work.

$name = pg_escape_string($_POST['name']); // Start destination from user input
$name2 = pg_escape_string($_POST['name2']); // End destination from user input

//If no results are given, the following query below will execute instead.

if (pg_num_rows($result) == 0 ) {

$query = "SELECT dt1.name as name1,dt1.time as time1,dt2.name as name2,dt2.time as time2
From departure_times as dt1
inner join departure_times as dt2 on dt2.tram_id = dt1.tram_id
where dt1.name = '$name' and dt2.name = 'CitySquare' LIMIT 5 

UNION 

SELECT dt1.name as name3,dt1.time as time3,dt2.name as name4,dt2.time as time4
From departure_times as dt1
inner join departure_times as dt2 on dt2.tram_id = dt1.tram_id
where dt1.name = 'CitySquare' and dt2.name = '$name2' LIMIT 5";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
} ...

The desired output:

------------------------------------------------------------------------
    name1 | time1  | name2  | time2 | name3 |  time3    | name4  | time4
------------------------------------------------------------------------

Viewing all articles
Browse latest Browse all 1138

Trending Articles