我有很多个表需要通过两个索引(每个表中都有这两项)做多表连接
要求查询出表1中所有项在其他表中对应的另一值
同时统计出两个索引项相同的值的个数
并排序
请问如何实现SQL语句
我试过如下语句不能成功为什么
select biao1.name,biao1.class,biao2.band(或者对应的表3、表4、表5的band项,各表中name 和 class对应的band 值可能重复,但name 加 class仅在其他表中的一个存在--要么在表2、要么在表3……),count(name) as 计数
from biao1 inner join biao2 on biao1.name=biao2.name and biao1.class=biao2.class,
     biao1 inner join biao3 on biao1.name=biao2.name and biao1.class=biao2.class,
     biao1 inner join biao4 on biao1.name=biao2.name and biao1.class=biao2.class,
     biao1 inner join biao5 on biao1.name=biao2.name and biao1.class=biao2.class
group by biao1.name,biao1.class
order bye biao1.name,biao1.class

解决方案 »

  1.   

    楼主的表连接语法是错误的,这样试试:
    select t1.name,t1.class,max(t2.band) as band,count(t1.name) as 计数
    from biao1 as t1 
    inner join biao2 as t2 on t1.name = t2.name and t1.class = t2.class
    inner join biao3 as t3 on t1.name = t3.name and t1.class = t3.class
    inner join biao4 as t4 on t1.name = t4.name and t1.class = t4.class
    inner join biao5 as t5 on t1.name = t5.name and t1.class = t5.class
    group by t1.name,t1.class
    order by 1,2        /*或order by t1.name,t1.class*/
      

  2.   

    具体表结构可以假定如下:
    表1:
    name class 
    1    1    
    1    2    
    2    1     
    2    2
    3    1
    3    2表2:
    name  class  band
    1       1     x
    1       1     y
    1       2     [null]
    1       3     z表3:
    name  class  band 
    2      1     [null]
    2      1      a
    2      2      d注:[null]代表空,就是说band列允许空值
    同时可以看到表2、表3中的name列与class列组合可以重复
    但表2中的组合与表3中的组合是互不相干的
    同时表1的表项不一定都出现在表2、表3中(如:name=‘3’)
    表2(或表3)重的name与class组合也不一定在表1中出现我现在要做的是查询形成如下表:
    name   class  band  重复数
    1        1      x     2
    1        1      y     2
    1        2    [null]  1
    1        3      z     1
    2        1    [null]  2
    2        1      a     1
    2        2      d     1
    3        1    [null]  1
    3        2    [null]  1我认为应该采用外连接 all outer join
    但是无法解决的是如何在后面把重复的次数列出来
    group by只能把分组或使用聚合函数的项显出
    同时每各分组只有一组数据
    与我的结果项是不符的!
    哪位达人能解答啊