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

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

但我只想显示第二个,即只参加过两个科目的人。我想使用内部连接。

4

2 回答 2

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时,这意味着它不存在与先前选择的子句不同的第三个。t3.nameNULLelective

如果存在第三个,则该where子句将删除那些names.

两者inner joins都存在select于至少两个不同的地方electives

于 2012-06-12T14:20:30.630 回答
1
SELECT id, name, COUNT(elective) FROM table GROUP BY id, name HAVING COUNT(elective) = 2
于 2012-06-12T14:19:53.550 回答