日期:2014-05-18  浏览次数:20632 次

求一条SQL语句?
一.求满足条件的前5条记录.
Menu_link表
ID       Title       parentID
1           人世间1     31
2           人世间2     31
4           人世间3     31
reco表
ID         title       parentID   ............
1           公司1           1
2           公司2           1
3           公司3           1
4           公司4           1
5           公司5           1
6           公司6           1
7           公司7           2
其中Menu_link表ID       对应reco表的parentID  


以下是我写的语句,显示reco表中符合条件的所有记录.但我只要
SELECT   *   FROM   reco   where   parentID   in(SELECT   id   FROM   Menu_Link   WHERE   (parentid   =   31)   )

------解决方案--------------------
--如果Menu_link表的parentid 都是31,可以不写这个条件(and a.parentid = 31).

create table Menu_link(ID int,Title varchar(10),parentID int)
insert into Menu_link values(1, '人世间1 ', 31)
insert into Menu_link values(2, '人世间2 ', 31)
insert into Menu_link values(4, '人世间3 ', 31)
go
create table reco(ID int,Title varchar(10),parentID int)
insert into reco values(1, '公司1 ', 1)
insert into reco values(2, '公司2 ', 1)
insert into reco values(3, '公司3 ', 1)
insert into reco values(4, '公司4 ', 1)
insert into reco values(5, '公司5 ', 1)
insert into reco values(6, '公司6 ', 1)
insert into reco values(7, '公司7 ', 2)
go

select m.* from Menu_link a,
(select * from reco as t where (select count(*) from reco where parentID = t.parentID and id < t.id) < 5) m
where a.id = m.parentid and a.parentid = 31

drop table Menu_link,reco

/*
ID Title parentID
----------- ---------- -----------
1 公司1 1
2 公司2 1
3 公司3 1
4 公司4 1
5 公司5 1
7 公司7 2

(所影响的行数为 6 行)
*/