Subquery with invalid identifier error in sql

大憨熊 提交于 2020-01-06 15:47:31

问题


want to select tour date and site names in advance of total cost is more than 230 and that tour has more than 7 persons. the complete code is below, the first part of union works.

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,tour_date,site_name, (res_partcost +NVL(RES_GEARCOST,0)) as "total_cost" 
  FROM reservation,site,tour) 
WHERE  reservation.tour_id = tour.tour_id
  AND tour.site_id = site.site_id
  AND total_cost > 230
GROUP BY tour_date, site_name;

I still got errors as

ORA-00904: "TOTAL_COST": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 437 Column: 7

Thanks


回答1:


You need to move your join conditions inside the subquery

SELECT tour_date AS "Departure Date",  site_name "Site Name"
FROM (
    SELECT res_id,tour_date,site_name, (res_partcost +NVL(RES_GEARCOST,0)) as "total_cost" 
    FROM reservation,site,tour
    WHERE reservation.tour_id = tour.tour_id
    AND tour.site_id = site.site_id ) Res1
WHERE Res1.total_cost > 230 // this will not be displayed in a result
GROUP BY tour_date, site_name;



回答2:


A union is not going to give you an "and" between the conditions. It is going to give you an "or" (because anything that matches either condition will be included).

I think you should phrase this as a single query, with subqueries. Also, proper join syntax is a benefit:

SELECT tour_date AS "Departure Date",  site_name "Site Name"
FROM partres p join
     reservation r
     on p.res_id = r.res_id join
     tour t
     on r.tour_id = t.tour_id and
        (res_partcost + coalesce(RES_GEARCOST,0)) > 230 join
     site s
     on t.site_id = s.site_id
GROUP BY tour_date, site_name
having COUNT(part_id) > 7;

This version is making a guess that total_cost is in the reservation table.



来源:https://stackoverflow.com/questions/16825262/subquery-with-invalid-identifier-error-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!