大类表:ClassTable
字段: cid,className(大类的id以及名称)
二类表:SortTable
字段:sid,sortName,clsName(二类的id、二类名称以及所属大类名称)
不是所有的大类下都有二类。怎么样实现如下效果?(没有二类的大类名称也显示)
(我用 select classname,sortname from classTable join sortTable on classname=clsname 只显示有二类的内容)
大类    二类
蔬菜    菠菜
蔬菜    韭菜
水果    苹果
水果    香蕉
水果    橘子
粮食
家禽    鸡
家禽    鸭
水产
副食

解决方案 »

  1.   

    select classname,sortname from classTable left join sortTable on classname=clsname
      

  2.   


    create table t1
    (
    id int,
    name varchar(10)
    )
    insert into t1
    select 1,'蔬菜' union all
    select 2,'水果' union all
    select 3,'粮食' union all
    select 4,'家禽' union all
    select 5,'水产' union all
    select 5,'副食'
    create table t2
    (
    id int,
    name varchar(10),
    pname varchar(10)
    )
    insert into t2
    select 1,'菠菜','蔬菜' union all
    select 1,'韭菜','蔬菜' union all
    select 1,'苹果','水果' union all
    select 1,'香蕉','水果' union all
    select 1,'橘子','水果' union all
    select 1,'鸡','家禽' union all
    select 1,'鸭','家禽'
    select * from t1
    select * from t2select t1.name,isnull(t2.pname,'') as pname from t1 left join t2 on t1.name=t2.pname-----------------------
    name pname
    蔬菜 蔬菜
    蔬菜 蔬菜
    水果 水果
    水果 水果
    水果 水果
    粮食
    家禽 家禽
    家禽 家禽
    水产
    副食 另外我建议楼主不要使用大类名称来关联大类和子类的关系,而是尽量使用大类编号。