在MySQL中将行转换为列

时间:2016-09-01 15:35:23

标签: mysql database join

我想将行转换为列(工作日名称),但每行只有一个条目,其余列为空(适用于教师和时间段)。

表格结构:

table structure

跟随查询的输出:

query result

我的查询是:

 SELECT
 /* Employee section */
 CONCAT(emp.first_name, " ",emp.middle_name,"", emp.last_name) as     employeeFullName,

/* Timetable Entry section */
CONCAT(ct.start_time," - ",ct.end_time) as Slots,

if(wd.name='Monday',CONCAT(sb.name," - ",bt.name),null) Monday,
if(wd.name='Tuesday',CONCAT(sb.name," - ",bt.name),null) Tuesday,
if(wd.name='Wednesday',CONCAT(sb.name," - ",bt.name),null) Wednesday,
if(wd.name='Thurseday',CONCAT(sb.name," - ",bt.name),null) Thurseday,
if(wd.name='Friday',CONCAT(sb.name," - ",bt.name),null) Friday,
if(wd.name='Saturday',CONCAT(sb.name," - ",bt.name),null) Saturday,
if(wd.name='Sunday',CONCAT(sb.name," - ",bt.name),null) Sunday 

FROM `timetable_entries` te 

left Join `weekdays` wd ON te.weekday_id=wd.id
left Join `employees` emp  ON te.employee_id=emp.id
left Join `class_timings` ct  ON te.class_timing_id=ct.id
left Join `batches` bt  ON te.batch_id=bt.id
left Join `subject` sb  ON te.subject_id=sb.id

WHERE te.employee_id is not null
Group By  te.class_timing_id,te.employee_id

1 个答案:

答案 0 :(得分:1)

我认为你应该改变整个思路。尝试这样的事情:

     SELECT
     /* Employee section */
     CONCAT(emp.first_name, " ",emp.middle_name,"", emp.last_name) as     employeeFullName,

    /* Timetable Entry section */
    CONCAT(ct.start_time," - ",ct.end_time) as Slots,
wd.name as weekDayName,
CONCAT(sb.name," - ",bt.name) as name

现在,您可以将每一天作为“weekDayName”访问,并将“name”作为concat。我认为这更容易,因为你没有你实际上不需要的列,这不会检查每行的“if”。