组合2个SELECT查询

时间:2016-03-03 20:33:48

标签: php sql database postgresql

所以我有2个查询,我想一起用来向用户提供一个输出结果。输出向用户描述了从A到B的过程。当我尝试将第一个查询的结果加入到第二个查询时,我不断收到语法错误。

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

我看了一个类似的问题,但解决方案&提供的讨论似乎不起作用。

$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

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;

$result = pg_query($query) or die('Query failed: ' . pg_last_error());

} .....


The desired output I am looking for is the following :

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

2 个答案:

答案 0 :(得分:2)

从它的外观来看,你想创建一个输出,列出从一些车站到城市广场的5辆电车和从城市广场到其他车站的5辆电车。在这种情况下 - 您没有在这两件事之间建立任何连接(例如,按时) - 您应该加入伪列,row_number() OVER ()会想到:

SELECT '$name' AS name1, w1.time1, 'City Square - arrival' AS name2, w1.time2,
       'City Square - departure' AS name3, w2.time3, '$name2' AS name4, w2.time4
FROM (
  SELECT dt1.time AS time1, dt2.time AS time2, row_number() OVER () AS rn
  FROM departure_times AS dt1
  JOIN departure_times AS dt2 USING (tram_id)
  WHERE dt1.name = '$name' AND dt2.name = 'CitySquare'
  LIMIT 5) w1
JOIN (
  SELECT dt1.time AS time3, dt2.time AS time4, row_number() OVER () AS rn
  FROM departure_times AS dt1
  JOIN departure_times AS dt2 USING (tram_id)
  WHERE dt1.name = 'CitySquare' AND dt2.name = '$name2'
  LIMIT 5) w2 USING (rn);

在每个子查询中,您可以选择五行。由于没有明显的属性,你可以JOIN这两组行,你必须创建一个可以达到这个目的的伪列(你需要一些东西可以加入,或者你会得到一个CROSS JOIN在输出中产生5 x 5行)。使用row_number() OVER () AS rn就是这样:它创建一个带有别名rn的新列,其中包含整个行集(OVER ()上的行号,由于LIMIT子句而包含5行)。您可以在两个子查询中执行此操作,以便将其用作连接条件:USING (rn)。您不必在输出中使用此列。

您无法控制将列出哪5个电车时间。如果您需要,您应该在两个子查询中执行类似WHERE dt1 > CURRENT_TIMEORDER BY dt1的操作,或者沿着该行执行某些操作。

答案 1 :(得分:0)

Abelisto已经为您提供了第一部分,在选择查询周围添加了括号。

对于问题的第二部分,如果您希望显示所有列,则需要在两个查询中包含所有列。所以添加null::text AS name3, null::timestamp AS time3等等。(请注意,我使用类型转换来猜测您的类型,您可能需要根据查询返回的类型进行更改。