按一列分组并显示多列

时间:2019-04-04 11:02:36

标签: mysql sql

我有一个表bschool_test_relation_domain,其列为testid,courseid,instid

  instid | Courseid  | testid
  23     |   35      | 45
  23     |   35      | 56
  33     |   45      | 68
  33     |   45      | 76
  33     |   45      | 86  

我需要通过inst_id和CourseID来获取具有group的行,然后检查testid来过滤数据。

 Select t1,instid,t1.courseid  
   from table1 as t1 
   JOIN 
      ( Select instid 
             , courseid 
          from bschool_test_relation_domain 
         group 
            by instid 
             , courseid ) t2 
     ON t2.instid = t1.instid 
    AND t2.courseid = t1.courseid 
  where t2.testid = 68

我想要的结果是

  instid | Courseid  | testid
  33     |   45      | 68

3 个答案:

答案 0 :(得分:0)

您可以尝试以下操作-使用min()

Select instid , courseid,min(testid)
from bschool_test_relation_domain 
where instid = 33
group by instid , courseid

答案 1 :(得分:0)

使用聚合函数min()不需要任何子查询

select  b.instid , b.courseid ,min(b.testid) testid
          from bschool_test_relation_domain b
           join table1 t on b.courseid=t.courseid and b.instid=t.instid
           where t.testid = 33
group by b.instid , b.courseid

答案 2 :(得分:0)

请尝试以下一种,希望它能起作用:

Select instid , courseid
from bschool_test_relation_domain
where orderby testid