2016-09-01 165 views
2

我想將行轉換爲列(星期幾名稱),但每行只有一個條目,而其餘列是空的(對於教師和時間段)。將行轉換爲MySQL列

表結構:

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 
+5

我很舒服「轉換成列」不是你想要的。這與關係數據庫的原理相矛盾。 –

+0

感謝您的回覆,抱歉讓人困惑,但我認爲問題從圖片和查詢中清楚! – sefburhan

+0

我沒有時間詳細闡述,但我認爲你需要從課堂時間開始查詢,並從08:00,09:00等開始每節課。從那裏你可以得到課程的細節,一週工作日,員工等 –

回答

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」,並有「名」爲CONCAT。我認爲這很容易,因爲你沒有列,你真的不需要,這不檢查每行的「如果」。

+0

感謝您的回覆,但我沒有顯示weekDayName,但任何與老師在給定的插槽相關的東西,我創建一個老師的時間表,我把週日作爲列,因爲它是固定的,其餘東西正在改變,所以請你能幫助我編寫一個查詢時間表,相關表在結構表中作爲外鍵提及,謝謝 – sefburhan