Reputation: 194
We have a table ta_service with following data
2340 1 Service 1
2340 2 Offer 1
2340 3 Service 2
2340 4 Offer 2
2340 5 Service 3
2340 5 Service 4
We have a requirement of fetching the services which has offers and we dont have any reference for getting this data apart from Ref_id(foreign key) and seq(Primary key) column.
We tried to fetch by following query but failed with that.
SELECT * FROM ta_service
WHERE Ref_id = 2340 AND seq IN (
SELECT seq-1 AS seq
FROM ta_service
WHERE Ref_id = 2340
AND desc LIKE '%Offer%'
UNION
SELECT seq AS seq
FROM ta_service
WHERE Ref_id = 2340
AND desc LIKE '%Offer%'
ORDER BY seq)
we are using sybase database. Any help appreciated
Upvotes: 2
Views: 4035
Reputation: 21
Here is the link to sybase manual which says UNION is not supported in subqueries: http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36272.1570/html/commands/X56548.htm
However I noticed that if we have the union clause within a derived table expression, then, it works fine. Here is the link to sybase manual which gives the syntax for the query: http://infocenter.sybase.com/archive/index.jsp?topic=/com.sybase.help.ase_15.0.sqlug/html/sqlug/sqlug418.htm
Example of failing and working query given below:
Mocked use case: Get employees from either department D1 or D2.
Failing query:
SELECT empname from emp WHERE deptid IN
(SELECT deptid from dept WHERE deptid = "D1"
UNION
SELECT deptid from dept WHERE deptid = "D2")
Working query: With additional select and derived table based on union:
SELECT empname from emp WHERE deptid IN (
SELECT deptid FROM
(SELECT deptid from dept WHERE deptid = "D1"
UNION
SELECT deptid from dept WHERE deptid = "D2") derivedTable
)
Upvotes: 2
Reputation: 1
ASE doesn't support UNION in a subquery as the 12.5 SQL manual I've just referred to confirms. It says "You cannot include a for browse clause or a union in a subquery." on page 169 in chapter 5. Another answer is correct even if the link was to IQ. I'd have left a comment but my account doesn't allow it.
Upvotes: 0
Reputation: 194
ASE doesn't support UNION in any subqueries.
You can refer the Sybase Documentation
Upvotes: 0
Reputation: 25753
You should remove order by
, and enclose desc
in "
because it's keyword
SELECT * FROM ta_service
WHERE Ref_id = 2340
AND seq IN (
SELECT seq-1 AS seq
FROM ta_service
WHERE Ref_id = 2340
AND "desc" LIKE '%Offer%'
UNION
SELECT seq AS seq
FROM ta_service
WHERE Ref_id = 2340
AND "desc" LIKE '%Offer%'
)
Upvotes: 1
Reputation: 6651
Assuming you are using ASE, your ORDER BY
needs to go outside the subquery.
From the Sybase Documentation:
•Subqueries cannot manipulate their results internally, that is, a subquery cannot include the order by clause, the compute clause, or the into keyword.
Upvotes: 1