我有 3 张桌子
TABLE "TUTOR"
TUTOR_ID NMAE
---------------
1 N1
2 N2
3 N3
4 N4
TABLE "TUTOR_SETTING"
TUTOR_ID MAX_STU_NUM
----------------------
1 5
2 6
TABLE "STU_TUTOR_MAPPING"
----------------------
STU_ID TUTOR_ID
A 1
B 2
C 1
D 1
我想将以下 3 个 sql 合并为一个 SQL:
1. SELECT * FROM TUTOR t1
2. SELECT * FROM TUTOR_SETTING t2 where t2.TUTOR_ID=t1.TUTOR_ID
3. SELECT COUNT(t3.STU_ID) FROM STU_TUTOR_MAPPING t3 WHERE t3.TUTOR_ID=t1.TUTOR_ID GROUP BY T1.TUTOR_ID
和预期的结果:从表“TUTOR”和JOIN“TUTOR_SETTING”中选择所有并加入“STU_TURTOR_MAPPING”并在具有相同tutor_id时计算“STU_TUTOR_MAPPING”的行。
TUTOR_ID NAME MAX_STU_NUM TOTAL_STU_NUM
-------------------------------------------------
1 N1 5 3
2 N2 6 1
3 N3 null
4 N4 null
我试过这样:
SELECT t1.TUTOR_ID, t1.NAME, t2.MAX_STU_NUM, count(t3.STU_ID)
FROM TUTOR t1
LEFT JOIN TUTOR_SETTING t2 on (t1.TUTOR_ID=t2.TUTOR_ID)
LEFT JOIN stu_tutor_mapping t3 on (t1.TUTOR_ID=t3.TUTOR_ID)
GROUP BY t1.TUTOR_ID, t1.NAME;
但是数据库报错:
ORA-00979: not a GROUP BY expression
00979. 00000 - "not a GROUP BY expression"
*Cause:
*Action:
Error at Line: 1 Column: 30
最后,我通过google解决了这个问题,这里是sql语句:
SELECT t1.TUTOR_ID, t1.NAME, t2.MAX_STU_NUM, t3.stu_allocated
FROM TUTOR t1
LEFT JOIN TUTOR_SETTING t2 on (t1.TUTOR_ID=t2.TUTOR_ID)
LEFT JOIN
(select tutor_id ,count(*) as TOTAL_STU_NUM from stu_turtor_mapping group by
tutor_id) t3 on t3.TUTOR_ID=t1.TUTOR_ID