0

我有 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
4

3 回答 3

3
SELECT  a.Tutor_ID,
        a.Name,
        COUNT(b.TUTOR_ID) TotalCount
FROM    Tutor a
        LEFT JOIN STU_TUTOR_MAPPING b
            ON a.Tutor_ID = b.TUTOR_ID
GROUP   BY a.Tutor_ID, a.Name

要进一步了解有关联接的更多信息,请访问以下链接:

上面的查询将显示表中的所有记录,TUTOR无论它在另一个表上是否没有匹配的记录,并将显示0为自使用以来的总计数LEFT JOIN。如果您想列出在另一个表上至少有 1 条匹配记录的所有记录,INNER JOIN就足够了。

SELECT  a.Tutor_ID,
        a.Name,
        COUNT(*) TotalCount
FROM    Tutor a
        INNER JOIN STU_TUTOR_MAPPING b
            ON a.Tutor_ID = b.TUTOR_ID
GROUP   BY a.Tutor_ID, a.Name
于 2013-05-14T07:00:07.410 回答
1

在您的查询中使用 Join 非常简单。如果你不知道 JOIN 那么链接 1. ,链接 2

于 2013-05-14T07:02:33.377 回答
0

你可以这样做 -

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, t2.MAX_STU_NUM
于 2013-05-14T07:07:40.110 回答