日期:2014-05-19  浏览次数:20564 次

求一排序的SQL语句
表1:pb_info     信息表

字段     infoId     title     orderNo   deptId
            信息ID     标题     排序序号     部门ID

表2:pb_dept   部门表

字段     deptId     deptName     orderNo
            部门ID     部门名称     排序序号

要求:deptId是表pb_info的外键,要求查询pb_info的内容,同时显示其所属部门名称,查询结果先按部门的排序序号进行排序,然后按信息排序序号进行排序。

例如:

部门A(PB_DEPT表中排序序号为1)
      信息1   (PB_INFO表中排序序号为1)
      信息3   (PB_INFO表中排序序号为3)
部门B(PB_DEPT表中排序序号为2)
      信息2   (PB_INFO表中排序序号为2)
      信息5   (PB_INFO表中排序序号为5)
部门C(PB_DEPT表中排序序号为3)
      信息4   (PB_INFO表中排序序号为4)

------解决方案--------------------
like this?

select t1.*,t2.deptName
from pb_info t1,pb_dept t2
where t1.deptId=t2.deptId
order by t2.orderNo,t1.orderNo
------解决方案--------------------
--這樣?
create table pb_info(infoId int, title varchar(20), orderNo int, deptId int)
insert pb_info select 1, '信息1 ', 1, 1
insert pb_info select 2, '信息3 ', 3, 1
insert pb_info select 3, '信息2 ', 2, 2
insert pb_info select 4, '信息5 ', 5, 2
insert pb_info select 5, '信息4 ', 4, 3


create table pb_dept(deptId int, deptName varchar(20), orderNo int)
insert pb_dept select 1, '部门A ', 1
insert pb_dept select 2, '部门B ', 2
insert pb_dept select 3, '部门C ', 3

select deptName, title from pb_dept
inner join pb_info on pb_info.deptId=pb_dept.deptId
order by pb_dept.orderNo, pb_info.orderNo

--result
deptName title
-------------------- --------------------
部门A 信息1
部门A 信息3
部门B 信息2
部门B 信息5
部门C 信息4

(5 row(s) affected)
------解决方案--------------------

create table pb_info(infoId int, title varchar(20), orderNo int, deptId int)
insert pb_info select 1, '信息1 ', 1, 1
insert pb_info select 2, '信息3 ', 3, 2
insert pb_info select 3, '信息2 ', 2, 3
insert pb_info select 4, '信息5 ', 5, 4
insert pb_info select 5, '信息4 ', 4, 5


create table pb_dept(deptId int, deptName varchar(20), orderNo int,parentId int)
insert pb_dept select 1, '部门A ', 1,0
insert pb_dept select 2, '部门B ', 2,0
insert pb_dept select 3, '部门C ', 3,0
insert pb_dept select 4, '部门D ', 1,1
insert pb_dept select 5, '部门E ', 2,1

select (CASE WHEN a.parentId=0 THEN c.deptName ELSE ' ' END),b.title,a.deptName from pb_dept a
inner join pb_info b on a.deptId=b.deptId
left join pb_dept c on a.parentId=c.deptId OR (a.deptId=c.deptId and a.parentId=0)
order by c.deptId,a.orderNo

title deptName
-------------------- -------------------- --------------------
部门A 信息1 部门A
信息5 部门D
信息4 部门E
部门B 信息3 部门B
部门C 信息2 部门C