0

私はMySQLで1つのプロジェクトを行っています。に 1 つの問題があり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 つ以上の科目を選択した人はほとんどおらず、2 つの科目だけを選択した人はほとんどいません。また、1 つの主題のみを選択した人もいます。

しかし、私は2番目のもの、つまり2つの科目のみを取得した人のみを表示したい. これは、内部結合を使用して取得したいです。

4

2 に答える 2

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

joinsOPが要求したようなもののみを使用:

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と同じt22 つの異なるを選択します。テーブルは別のものを選択します。したいという節を入れると、前に選択したものとは3分の1異なるものが存在しないことを意味します。electivesid/persont3electivewheret3.nameNULLelective

3番目のものが存在する場合、where句はそれらを削除しnamesます。

この 2 つinner joinsselect、少なくとも 2 つの異なる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 に答える