复合连接仅用于选择两个主题

时间:2012-06-12 14:14:07

标签: mysql sql join

我在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 | 
+---+-----------+-----------+

在上表中,很少有人选择了两个以上的科目而很少有人选择了两个科目。其他人只选择了一个主题。

但是我想只显示第二个,即只拍摄两个科目的人。我希望使用内连接。

2 个答案:

答案 0 :(得分:3)

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

仅使用像我们要求的joins

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条款时,我希望t3.nameNULL,这意味着它不存在与之前选择的第三个elective不同的。{ / p>

如果存在第三个where子句将删除names

两个inner joinsselect至少有两个electives

答案 1 :(得分:1)

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