How to combine three tables result by one SQL query -


i have 3 tables

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         1 b         2 c         1 d         1 

and want combile below 3 sql 1 sql:

1. select * tutor t1 2. select * tutor_setting t2 t2.tutor_id=t1.tutor_id 3. select count(t3.stu_id) stu_tutor_mapping t3 t3.tutor_id=t1.tutor_id group t1.tutor_id 

and expected result: select table "tutor" , join "tutor_setting" , join "stu_turtor_mapping" , count rows of "stu_tutor_mapping" when there have same tutor_id.

tutor_id    name     max_stu_num    total_stu_num ------------------------------------------------- 1           n1       5              3 2           n2       6              1 3           n3       null 4           n4       null 

i tried way:

select t1.tutor_id, t1.name, t2.max_stu_num, count(t3.stu_id) 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 t1.tutor_id, t1.name; 

but database report error:

ora-00979: not group expression 00979. 00000 -  "not group expression" *cause:     *action: error @ line: 1 column: 30 

finally, resolve issue google, here sql statement:

select t1.tutor_id, t1.name, t2.max_stu_num, t3.stu_allocated tutor t1    left join tutor_setting t2 on (t1.tutor_id=t2.tutor_id)    left join     (select tutor_id ,count(*) total_stu_num stu_turtor_mapping group     tutor_id) t3 on t3.tutor_id=t1.tutor_id 

select  a.tutor_id,         a.name,         count(b.tutor_id) totalcount    tutor         left join stu_tutor_mapping b             on a.tutor_id = b.tutor_id group   a.tutor_id, a.name 

to further gain more knowledge joins, kindly visit link below:

the query above display records table tutor whether has no matching record on other table , display 0 total count since using left join. if want list records has atleast 1 matching record on other table, inner join suffice.

select  a.tutor_id,         a.name,         count(*) totalcount    tutor         inner join stu_tutor_mapping b             on a.tutor_id = b.tutor_id group   a.tutor_id, a.name 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -