One-to-many two tables, query the information of the main table and the number of records in the sub-table of the main table

You may not understand from the title. For example

Table A is a class table, fields: ID=class number, Name=class name

Table B is a student table with fields: ID=class ID, SID=student ID.

 

It is to query all the information of the class table, and then query the number of students corresponding to the class table. Ask in the group, there are two relatively simple and clear ways to summarize

The first method (castle lord):

select a.*, (select count(*) from b where b.ID=a.id) as 学生数量  from  a

This looks clearer and simpler.

 

The second method (tear kiss star marks):

select a.*,
xx.number from a, (select b.ID,count(ID) as number from b group by b.ID) xx
where a.ID = xx.ID
This method uses a temporary table, which is equivalent to First construct a temporary table, and then use class table A to associate with the temporary table

 

Tears Kiss Star Mark recommends the second method, because the correlation query is fast, and he has also tested it. I'm currently busy with a project, and I haven't tested and compared the two performances myself.

 

But in fact, the results of the two sql queries are different

Using the first method,

Query the class information and the number of students corresponding to the class. Record with class information even if the number of students is 0

The second method is that if the number of students is 0, the corresponding class information will not be displayed.

But this is a small problem, as long as you modify the join relationship

select a.*,xx.人数
from  a left join  (select b.ID,count(ID) as 人数 from b group by b.ID) xx
on a.ID = xx.ID

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325258378&siteId=291194637