问题
I need a UNION
of two queries, each of them works separatly, but not together, I get error: duplicate column name zipcode_id
, please help.
(SELECT * FROM
( (SELECT * FROM jobs AS j LEFT JOIN zipcode AS z ON z.zipcode_id=j.zipcode_id WHERE 1 AND source='student'
ORDER BY postdate DESC LIMIT 20) ORDER BY search_order DESC )
s1)
UNION ALL
(SELECT * FROM
( (SELECT * FROM jobs AS j LEFT JOIN zipcode AS z ON z.zipcode_id=j.zipcode_id WHERE 1 AND source='manager'
ORDER BY postdate DESC LIMIT 30, 1000000) ORDER BY postdate DESC )
s2)
回答1:
You may need to use different alias names for each sub-query. This should work:
(SELECT * FROM
( (SELECT j1.* FROM jobs AS j1 LEFT JOIN zipcode AS z1 ON z1.zipcode_id=j1.zipcode_id WHERE 1 AND source='student'
ORDER BY postdate DESC LIMIT 20) ORDER BY search_order DESC ) s1) UNION ALL
(SELECT * FROM
( (SELECT j2.* FROM jobs AS j2 LEFT JOIN zipcode AS z2 ON z2.zipcode_id=j2.zipcode_id WHERE 1 AND source='manager'
ORDER BY postdate DESC LIMIT 30, 1000000) ORDER BY postdate DESC )
s2)
回答2:
If you're actually using SELECT *
then the zipcode_id
column is in both the Jobs
table and the Zipcode
table. As the error message says, you can't have the two columns using the same name as you have it. Because you are using subqueries there would be no way for the SQL engine to understand what you meant if you referred to the duplicated column name. For example, what should the following SQL return?
SELECT num FROM (SELECT 1 AS num, 2 AS num) AS SQ
Using SELECT *
is a pretty bad practice in any event.
来源:https://stackoverflow.com/questions/7664378/sql-union-of-two-queries-duplicate-column-name-error