到目前为止,我有以下内容:
SELECT D.department AS dept, C.name AS subdept
FROM (SELECT DISTINCT department FROM classes WHERE web != 0 ORDER BY department,name LIMIT 5) D
LEFT JOIN classes C ON (C.department = D.department)
ORDER BY D.department,C.name
结果如下:
+------+-------------------------------+
| dept | subdept |
+------+-------------------------------+
| BOOK | CHILDRENS BOOKS |
| BOOK | DVD'S |
| CLOT | ACCESSORIES |
| CLOT | APRONS |
| FEED | BIBS & BURP CLOTHS |
| FEED | BOTTLE & FOOD WARMERS |
+------+-------------------------------+
我试图获得的是每个部门的“标题”,其子部门值为空,例如:
+------+-------------------------------+
| dept | subdept |
+------+-------------------------------+
| BOOK | null |
| BOOK | CHILDRENS BOOKS |
| BOOK | DVD'S |
| CLOT | null |
| CLOT | ACCESSORIES |
| CLOT | APRONS |
| FEED | null |
| FEED | BIBS & BURP CLOTHS |
| FEED | BOTTLE & FOOD WARMERS |
+------+-------------------------------+
表的结构: 部门表具有 id 主键,以类部门字段作为外键。
部门:id | 名称(部门) 类:部门 | 姓名(班级)
根据 DanfromGermany 向我展示的内容,我有:
SELECT D.department AS dept, C.name AS subdept
FROM
(SELECT DISTINCT department FROM classes WHERE web != 0 ORDER BY department,name LIMIT 5) D
LEFT JOIN classes C ON (C.department = D.department)
GROUP BY D.department, C.name WITH ROLLUP
现在给出:
+--------+-------------------------------+
| dept | subdept |
+--------+-------------------------------+
| BOOK | CHILDRENS BOOKS |
| BOOK | DVD'S |
| BOOK | [NULL] |
| CLOT | ACCESSORIES |
| CLOT | APRONS |
| CLOT | [NULL] |
| FEED | BIBS & BURP CLOTHS |
| FEED | BOTTLE & FOOD WARMERS |
| FEED | [NULL] |
| GEAR | BOOSTER CAR SEATS |
| GEAR | CAR SEAT ACCESSORIES |
| GEAR | [NULL] |
| GIFT | BABY BASKETS & DIAPER CAKES |
| GIFT | BANKS |
| GIFT | [NULL] |
| [NULL] | [NULL] |
+--------+-------------------------------+
好的最后编辑:
它通过子查询来使用 order by:
SELECT * FROM
(SELECT D.department AS dept, C.name AS subdept
FROM
(SELECT DISTINCT department FROM classes WHERE web != 0 ORDER BY department,name LIMIT 5) D
LEFT JOIN classes C ON (C.department = D.department)
GROUP BY D.department, C.name WITH ROLLUP
) T
ORDER BY dept,subdept