2012-06-12 21 views
0

我正在做一個項目在MySQL中。我遇到一個問題join複雜的連接只能選擇兩個主題

+---+-----------+-----------+ 
|id | name  | elective | 
+---+-----------+-----------+ 
| 1 | Jone  | Math  | 
| 2 | Jane  | Math  | 
| 3 | Doe  | Math  | 
| 4 | Bloggs | Math  | 
| 5 | Peter  | Math  | 
| 6 | Chris  | Math  | 
| 7 | Mark  | Math  | 
| 3 | Doe  | Physics | 
| 4 | Bloggs | Physics | 
| 5 | Peter  | Physics | 
| 6 | Chris  | Physics | 
| 7 | Mark  | Physics | 
| 5 | Peter  | Chemistry | 
| 6 | Chris  | Chemistry | 
| 7 | Mark  | Chemistry | 
+---+-----------+-----------+ 

在上表中,很少有人選擇了兩個以上的科目,其他人只有兩個科目。而其他人只選擇了一個主題。

但我只想顯示第二個,即只有兩個主題的人。這我想要使用內部連接。

+0

爲什麼有人會毀了我的一個很好的編輯?現在看起來很糟糕。 –

+0

請修復表格結構。這個數據可以用多於一種方式解釋:( –

回答

1
SELECT id, name, COUNT(elective) FROM table GROUP BY id, name HAVING COUNT(elective) = 2 
+0

呃,這個問題是由誰製作的,不適合DB結構的類3,應該立即重新考慮,顯然應該只保存'person_id ,subject_id'並且有外鍵 –

+0

你的錯誤比我的錯,但是我得到了錯誤信息,因爲我的信譽較低,看起來很公平:/ –

+1

+1查詢從頭開始正確 –

3
select id, name from tablename 
group by id, name 
having count (elective) = 2 

只使用joins像OP要求:

select t1.id, t1.name 
from tablename t1 
inner join tablename t2 on t2.id = t1.id and t2.name = t1.name and t2.name <> t1.name 
left outer join tablename t3 on t3.id = t2.id and t3.name <> t1.name and t3.name <> t2.name 
where t3.name is null 

t1t2選擇兩個不同的electives爲同一id/person。表t3將選擇另一個elective。當我將where子句放入爲NULL這意味着它不存在不同於之前選擇的第三個elective

如果存在第三個,where子句將刪除那些names

這兩個inner joins出現在select至少有兩個不同的electives

+0

並沒有冒犯,但你的查詢也不會工作,因爲可以有兩個同名的人。 –

+0

很高興我們同意表結構是可怕的,需要修復。 –

+0

謝謝,但我想用mysql的結果加入 – balamurugan