首页 > 解决方案 > 多行数据作为单个查询结果 - My SQL

问题描述

需要将多个行值作为单个结果获取。

餐桌人员

staffID, staffname
1         John
2         Smith 

课程表

 courseId, staffId, courseId, courseDesc
    1            1      3           Chemistry
    2            1      4           Physics
    3            1      5           Math
    4            2      6           Science

预期成绩:

 staffId, staffName, isScience, isMath, isPhyscis, isChemistry
      1       John        false      true   true        true

标签: mysqlsqljoinpivot

解决方案


您可以加入和使用条件聚合:

select
    s.id,
    s.name,
    max(coursedesc = 'Science'  ) isScience,
    max(coursedesc = 'Math'     ) isMath,
    max(coursedesc = 'Physics'  ) isPhysics,
    max(coursedesc = 'Chemistry') isChemistry
from staff s
left join course c on c.staffid = s.id
group by s.id, s.name

这会将0/1值放在附加列中,这与 MySQL 中的布尔值非常接近。


推荐阅读