两个查询的 SQL UNION,重复列名错误
我需要两个查询的 UNION
,每个查询单独工作,但不能一起工作,我收到错误:重复的列名 zipcode_id
,请帮忙。
(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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您实际上使用的是
SELECT *
,则zipcode_id
列同时位于Jobs
表和Zipcode
表中。正如错误消息所示,您不能让两列使用与您拥有的名称相同的名称。因为您正在使用子查询,所以如果您引用重复的列名,SQL 引擎将无法理解您的含义。例如,以下 SQL 应该返回什么?无论如何,使用 SELECT * 是一种非常糟糕的做法。
If you're actually using
SELECT *
then thezipcode_id
column is in both theJobs
table and theZipcode
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?Using
SELECT *
is a pretty bad practice in any event.您可能需要为每个子查询使用不同的别名。这应该有效:
You may need to use different alias names for each sub-query. This should work: