I have two SELECT statment which I connect using UNION
and I get error
ORA-00904: "PUSD2"."STARTDATE": invalid identifier
Since I create first one SELECT statment and run and I get result, and second also, so I run separatly and it works perfect. But when I use UNION I get error pusd2.StartDate invalid identifier.
SELECT * FROM project_users_schedule_dates pusd1 WHERE pusd1.UserID = 196 AND pusd1.StartDate >= '2020-04-27' AND pusd1.EndDate <= '2020-06-06' UNION SELECT * FROM project_users_schedule_dates pusd2 WHERE pusd2.UserID = 196 AND pusd2.StartDate <= '2020-04-27' AND pusd2. EndDate >= '2020-06-06' ORDER BY pusd2.StartDate
What is wrong here ? What I made wrong ?
Table structure project_users_schedule_dates
Advertisement
Answer
The error likely stems from using an alias in the second union in your ORDER BY
clause. However, I might suggest writing your query this way instead:
SELECT DISTINCT * FROM project_users_schedule_dates WHERE UserID = 196 AND (StartDate >= '2020-04-27' AND EndDate <= '2020-06-06' OR StartDate <= '2020-04-27' AND EndDate >= '2020-06-06');
This approach brings together the critera from both sides of the union in a single WHERE
clause. It then filters duplicates using DISTINCT
, instead of the union. Note that in general doing SELECT *
in a union query is not desirable, because it makes it impossible to see which columns are being included.