使用Union但我的现有列有错误作为无效标识符

时间:2013-05-29 05:52:23

标签: sql union

我正在使用union,当写这样的查询时,

    SELECT tour_date AS "Departure Date",  site_name "Site Name" FROM partres, reservation, tour, site
WHERE partres.res_id = reservation.res_id
  AND reservation.tour_id = tour.tour_id
  AND tour.site_id = site.site_id
GROUP BY tour_date, site_name
HAVING COUNT(part_id) > 7

  UNION

SELECT tour_date AS "Departure Date",  site_name "Site Name"
FROM (
  SELECT res_id, (res_partcost +NVL(RES_GEARCOST,0)) AS "total_cost" 
  FROM reservation) tour, site
WHERE  reservation.tour_id = tour.tour_id
  AND tour.site_id = site.site_id
  AND total_cost > 230
GROUP BY tour_date, site_name;

但它显示错误为

ORA-00904: "TOUR_DATE": invalid identifier

00904。 00000 - “%s:无效标识符” *原因:
*行动: 行错误:305列:10

所以我不知道为什么我的现有专栏有错误。

1 个答案:

答案 0 :(得分:0)

在联盟的后半部分中, 没有tour_date列来自该子选择。

在这种情况下,您的tour“表格”不是实际的表格,而是内部选择的结果,它仅提供res_idtotal_cost

我的意思是:

SELECT tour_date AS "Departure Date",  site_name "Site Name"
FROM (
  SELECT res_id, (res_partcost +NVL(RES_GEARCOST,0)) AS "total_cost" 
  FROM reservation) tour, site ...

会给你两个“表”来获取列。第二个表格是site,这可能是site_name的来源,尽管你真的应该用site.site_name明确强制执行,因为它会更明显。

现在这很重要。即使您拥有一个名为tour的真实表,您选择的事实是:

(SELECT res_id, (res_partcost +NVL(RES_GEARCOST,0)) AS "total_cost"
 FROM reservation) tour

表示您的查询视为tour的内容不是tour表。它实际上是括号内的查询。因此,tour在这种情况下包含res_idtotal_cost列,但看不到tour_date

如果要从子选择中选择内容,则需要确保名称匹配。