2010-10-24 46 views
0

连接使用我有这两个表:MySQL的问题与工会/结合

表作者:

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

表合着:

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的gves我一个错误说:ERROR 1060 (42S21): Duplicate column name 'ID'

为什么会出现这种情况,如何避免呢?

回答

2

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

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; 

因为你不需要从合着的ID列,你可以只是没有在内部查询选择它。这应该删除重复的列错误,因为它只选择ID列中的一列。

+0

这摆脱了这个问题,但现在NumPapers始终返回1.这是为什么?我使用了Will A的解决方案,并且保留了我的工会,而且它似乎工作正常。 – 2010-10-24 23:05:56

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;