[英]MySql select data from multiple tables - several sub records expected
我有一種錯誤的感覺,那就是表結構有誤,因此對您的幫助將不勝感激。
我有三個桌子
tbl_A (has class and section association)
ID
classid
sectionid
tbl_B (has subject and class association)
ID
classid
subjectid
tbl_C (has examination and class association)
ID
classid
examid
我需要以以下格式顯示記錄
Class | Section (s) | Subject (s) | Examination (s)
---------------------------------------------------
Grade 1 | A, B, C, D | English, Maths, Drawing... | Assessment 1, Assessment 2...
SQL腳本
SELECT DISTINCT t1.classid, t1.sectionid, t2.subjectid, t3.examid
FROM `tbl_A` As t1
JOIN `tbl_B` t2 ON t1.classid = t2.classid
JOIN `tbl_C` t3 ON t1.classid = t3.classid
上面的內容可以通過一個SQL QUERY(帶有join等)來實現,還是需要創建帶有記錄集的單獨SQL來遍歷(例如,Grade 1將具有多個主題,等等)
預先感謝堆積!
SELECT t1.classid,
group_concat(t1.sectionid order by t1.sectionid),
group_concat(t2.subjectid order by t1.sectionid),
group_concat(t3.examid order by t1.sectionid)
FROM `tbl_A` As t1
JOIN `tbl_B` t2 ON t1.classid = t2.classid
JOIN `tbl_C` t3 ON t1.classid = t3.classid
group by t1.classid
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.