我在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 :(得分: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
表t1
和t2
为同一electives
选择两个不同的id/person
。表t3
将选择另一个elective
。当我输入where
条款时,我希望t3.name
为NULL
,这意味着它不存在与之前选择的第三个elective
不同的。{ / p>
如果存在第三个where
子句将删除names
。
两个inner joins
至select
至少有两个electives
。
答案 1 :(得分:1)
SELECT id, name, COUNT(elective) FROM table GROUP BY id, name HAVING COUNT(elective) = 2