2010-10-24 23 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;