SQL UNION of two queries, duplicate column name error

走远了吗. 提交于 2021-01-27 14:32:56

问题


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

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