mainTable中table1-ID,table2-ID,table3-ID其中的一项或者两项可能为空,现在要查询mainTable,要求查询的结果如下:
ID table1-Name table2-Name table3-Name
为了增强用户体验,采用分页显示,每次取几十条记录,像这种SQL语句该怎么写呢?
分享到:更多
------解决方案--------------------
select
m.id,a.name as table1-name,b.name as table2-name,c.name as table3-name
from maintable m
inner join table1 a on m.table1-ID=a.table1-ID
inner join table2 b on m.table2-ID=b.table1-ID
inner join table3 c on m.table3-ID=c.table1-ID
where m.id between m and n
在maintable的id字段建立聚集索引,table1-ID-table3-ID建立非聚集索引table1-table3的id字段一样建立聚集索引
CREATE PROCEDURE [存储过程名]
@page_size INT = 50,
@page_index INT = 1
AS
BEGIN
declare @page_start INT
declare @page_end INT
SET @page_start = @page_size * (@page_index - 1) + 1
SET @page_end = @page_size + @page_start - 1
select * from mainTable t
WHERE t.ID between @page_start and @page_end
order by t.ID
select * from
(
select row_number()over(order by createtime ) as rownum,
m.id,a.name as table1-name,b.name as table2-name,c.name as table3-name
from maintable m
inner join table1 a on m.table1-ID=a.table1-ID
inner join table2 b on m.table2-ID=b.table1-ID
inner join table3 c on m.table3-ID=c.table1-ID
) where rownum>10 and rownum<=20 ------解决方案--------------------