如何选择所有行都具有的行ID

时间:2019-09-09 10:18:47

标签: mysql sql

有一张桌子:

+-------------+----------+
|stud_group_id|subject_id|
+-------------+----------+
|    1g       |   1s     |
+-------------+----------+
|    1g       |   2s     |
+-------------+----------+
|    1g       |   3s     |
+-------------+----------+
|    2g       |   1s     |
+-------------+----------+
|    2g       |   2s     |
+-------------+----------+
|    3g       |   1s     |
+-------------+----------+
|    3g       |   2s     |
+-------------+----------+
|    3g       |   4s     |
+-------------+----------+

我需要选择所有subject_id学到的stud_group_id。 我希望

+----------+
|subject_id|
+----------+
|   1s     |
+----------+
|   2s     |
+----------+

我该怎么做?谢谢

5 个答案:

答案 0 :(得分:1)

尝试这个:

select 
    subject_id,
    count(distinct stud_group_id) as cnt
from
    <your_table>
group by
    subject_id
having cnt=(select count(distinct stud_group_id) from <your table>)

答案 1 :(得分:1)

大致情况:

select count(stud_group_id) as num_learners_from_group, subject_id 
    from your_table group by subject_id 
    having num_learners_from_group = 
      (select count(*) 
         from stud_groups_table 
         where stud_groups_table.stud_group_id = your_table.stud_group_id
         group by stud_groups_table.stud_group_id)

答案 2 :(得分:1)

您可以使用having子句,如下所示:

select subject_id         
  from tab
 group by subject_id
having count(distinct stud_group_id) = ( select count(distinct stud_group_id) from tab )

Demo

答案 3 :(得分:0)

您尚未提及表名,因此使用TABLE_NAME作为占位符。

select distinct subject_id from TABLE_NAME group by stud_group_id, subject_id

答案 4 :(得分:0)

希望这对您有用:

select subject_id
from mytable
group by subject_id
having count(*) = (select count(distinct stud_group_id) from mytable)