当前位置: 代码迷 >> Sql Server >> sql 语句求解,表循环的有关问题
  详细解决方案

sql 语句求解,表循环的有关问题

热度:25   发布时间:2016-04-27 21:12:39.0
sql 语句求解,表循环的问题
二个表     cat   class
表结构及数据
cat   表
cat_id           cat_name     cat_prd_id
1                     cat_1           cat_prd_1
2                     cat_2           cat_prd_2

class   表
class_id       class_name     class_prd_id                 cat_prd_id
1                     class_1           class_prd_1                   cat_prd_1
2                     class_2           class_prd_2                   cat_prd_1
3                     class_3           class_prd_3                   cat_prd_1
4                     class_4           class_prd_4                   cat_prd_2
5                     class_5           class_prd_5                   cat_prd_2

表结构说明
可以看做一个大类表,一个分类表。大类和分类表通过cat_prd_id关联。
大类的记录唯一,属于该大类的分类可能有N个

希望得到的结果
在大类(CAT)表循环的过程中,如果检测到分类(class)表中有属于该大类的记录则显示出来,在asp   中可以很好的用循环做出来,但现在因为这2个表的数据量非常大,如果用asp的do   while   not   循环来做的话太耗资源,看能否通过一条select语句完成。
结果类似如下
1                     cat_1           cat_prd_1
1                     class_1           class_prd_1                   cat_prd_1
2                     class_2           class_prd_2                   cat_prd_1
3                     class_3           class_prd_3                   cat_prd_1
2                     cat_2           cat_prd_2
4                     class_4           class_prd_4                   cat_prd_2
5                     class_5           class_prd_5                   cat_prd_2


------解决方案--------------------
select class_id , class_name, class_prd_id , cat_prd_id from class
where exists(select 1 from cat where cat_prd_id=class.cat_prd_id)
union all
select cat_id , cat_name , cat_prd_id, ' ' from cat

order by case when cat_prd_id= ' ' then 1 else 2 end, class_id
------解决方案--------------------
簡化下,可以這麼寫

Select * From class Where cat_prd_id In (Select cat_prd_id From cat)
  相关解决方案