如何通过一个SQL查询组合三个表

时间:2013-05-14 06:58:02

标签: sql

我有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”中选择all并加入“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

最后,我通过谷歌解决了这个问题,这里是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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

它如此简单的使用加入您的查询。 如果您不了解加入,请Link 1.Link 2

答案 2 :(得分: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