一个年级有n个班级,每个班级有m个同学,数据库只有两个表:
tbclass(id,classname)和tbstudent(id,studentname,classid)。现在要在一个页面显示出这个年级的所有学生名单,效果如下:一班:
张三、李四......二班:
A1,A2,A3.....三班:
a,b,c,d.....我现在只有一个办法,就是用for循环,先读一次数据库,读出所有班级,然后用程序for循环,依次读取每个班级的全部学生名单。但这有一个问题,一个班级需要读一次数据库,如果有20班,岂不是一共要读21次数据库?这样效率是不是很低?有没有办法一次性读出所有学生,但在程序上能够分开每个班级。或者读尽量少的数据库?就像读取全中国的大城市一样,不可能每个省读一次数据库吧,应该是一次性读出来。

解决方案 »

  1.   

    union all

    合并字符串
      

  2.   

    select id , name from
    (
    select id,classname name , px1 = 1 ,px1 = id from tbclass
    union all
    select id,studentname name , px2 = 2,px2 = classid from tbstudent
    ) t
    order by px2 , px1
      

  3.   

    --创建班级表
    if object_id('tbclass') is not null
    drop table tbclass
    create table tbclass(id int,classname nvarchar(20))
    go
    --创建学生表
    if object_id('tbstudent') is not null
    drop table tbstudent
    create table tbstudent(id int,studentname nvarchar(20),classid int) 
    goinsert into tbclass
    select 1,N'一班' union
    select 2,N'二班' union
    select 3,N'三班'  
    go
    insert into tbstudent
    select 1,N'张三',1 union
    select 2,N'李四',1 union
    select 3,N'A1',2 union
    select 4,N'A2',2 union
    select 5,N'A3',2 union
    select 6,N'a',3 union
    select 7,N'b',3 union
    select 8,N'c',3 
    go
    Select C.classname,S.studentName 
    from tbclass C
    left join tbstudent S on C.id=S.classid
    order by C.ID 
      

  4.   

    --创建班级表
    if object_id('tbclass') is not null
    drop table tbclass
    create table tbclass(id int,classname nvarchar(20))
    go
    --创建学生表
    if object_id('tbstudent') is not null
    drop table tbstudent
    create table tbstudent(id int,studentname nvarchar(20),classid int) 
    goinsert into tbclass
    select 1,N'一班' union
    select 2,N'二班' union
    select 3,N'三班'  
    go
    insert into tbstudent
    select 1,N'张三',1 union
    select 2,N'李四',1 union
    select 3,N'A1',2 union
    select 4,N'A2',2 union
    select 5,N'A3',2 union
    select 6,N'a',3 union
    select 7,N'b',3 union
    select 8,N'c',3 
    go--drop function f_getstr
      if object_ID('f_getstr') is not null
    drop function f_getstr
      go
      create   function   f_getstr(@id int)   
      returns   varchar(8000)   
      as     begin   
      declare   @Str   nvarchar(4000)   
      set   @str   =   ''   
      select   @str   =   @str   +   studentName + ','   from   tbstudent where classid =@id   set @str = left(@str,len(@str)-1)
      return @str  
      end
      go 
    Select C.classname,dbo.f_getstr(C.id) as 人
    from tbclass C 一班 张三,李四
    二班 A1,A2,A3
    三班 a,b,c