MySql从多个表中选择数据 - 预期的几个子记录

时间:2015-06-13 10:09:53

标签: mysql multiple-tables nested-queries

我有一种感觉我可能有错误的表结构,所以任何帮助将不胜感激。

我有三张桌子

    var app = angular.module('stack', []);

    app.directive('filterList', function ($timeout) {
        return {
            link: function (scope, element, attrs) {

                var td = Array.prototype.slice.call(element[0].children);

                function filterBy(value) {
                    td.forEach(function (el) {
                        el.className = el.cells[3].textContent.toLowerCase().indexOf(value.toLowerCase()) !== -1 ? '' : 'ng-hide';
                    });
                }

                scope.$watch(attrs.filterList, function (newVal, oldVal) {
                    if (newVal !== oldVal) {
                        filterBy(newVal);
                    }
                });
            }
        };
    });

我需要以下列格式显示记录

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

SQL SCRIPT

Class | Section (s) | Subject (s) | Examination (s)
--------------------------------------------------- 
Grade 1 | A, B, C, D | English, Maths, Drawing... | Assessment 1, Assessment 2... 

上面的内容可以通过一个SQL QUERY(使用join等)实现,还是需要创建单独的SQL来跟踪记录集(例如,1级将有多个主题等)

提前谢谢!

1 个答案:

答案 0 :(得分:0)

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