与union / join一起使用的mysql问题

时间:2010-10-24 21:59:42

标签: mysql join union

我有这两个表:

表作者:

ID (INTEGER),
author_name (VARCHAR),
first_name (VARCHAR),
last_name (VARCHAR),
preferred_name (VARCHAR)

表格CoOuthored:

ID (INTEGER)
author1ID (INTEGER),
author2ID (INTEGER),
paper_ID (INTEGER) // (ID of the co-authored paper referenced by this link)

如您所见,两个表都有一个列'ID',但它们是不相关的。

但是,当我使用此查询时:

select author_name, count(*) as NumPapers from
(select * from Author as a join CoAuthored as c on a.ID = c.author1ID
union distinct
select * from Author as b join CoAuthored as d on b.ID = d.author2ID) as t1
group by author_name
order by NumPapers;

mySQL给我一个错误说:ERROR 1060 (42S21): Duplicate column name 'ID'

为什么会发生这种情况,我该如何避免呢?

3 个答案:

答案 0 :(得分:2)

而不是select * ...在联合的两个子查询中使用select author_name ...。问题源于AuthorCoAuthored都有ID列。 SELECT *带来了这两个列,MySQL不喜欢UNIONing这些产生带有两个同名列的结果集的想法。

答案 1 :(得分:1)

试试这个:

select author_name, count(*) as NumPapers from 
(
    select a.id, a.author_name from Author as a 
    join CoAuthored as c on a.ID = c.author1ID
    union distinct
    select b.id, b.author_name from Author as b
    join CoAuthored as d on b.ID = d.author2ID
) as t1
group by author_name
order by NumPapers;

由于您不需要CoAuthored中的ID列,因此您无法在内部查询中选择它。这应该删除您的重复列错误,因为它只选择了1个ID列。

答案 2 :(得分:1)

怎么样:

SELECT author_name, COUNT(*) AS NumPapers
  FROM Author AS a
  JOIN CoAuthored AS c ON a.ID = c.author1ID OR a.ID = c.author2ID
 GROUP BY author_name
 ORDER BY NumPapers;