Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to get range of results in alphabetical order

I have a table, tblTags which works in much the same way as StackOverflows tagging system.

When I view a tags page, let's say the tag Tutorial I want to display the 10 tags before and after it in alphabetical order.

So if we are given the tag Tutorial of ID 30 how can we return a record set in the order resembling:

Tap
Tart
> Tutorial
Umbrellas
Unicorns
Xylaphones

I have thought of ways of doing this, badly, in my opinion as they involve retrieving ugly amounts of data.

I'm not sure if it's possible to do something along the lines of (pseudo):

SELECT RANGE(0 - 30) FROM tblTags ORDER BY Name ASC

But how do you know the position of the tutorial tag in the list in an efficient manner without traversing the entire list until you find it?

I'm using SQL Server 2008 R2 Express with LINQ if it makes any difference, SQL queries or LINQ would be great answers, thanks!

like image 947
Tom Gullen Avatar asked Dec 27 '22 18:12

Tom Gullen


1 Answers

Building off Jacob's UNION suggestion, you use a table variable to select the matching TagID's into and then join back against the Tag table to get the matching records. It's not as elegant as I would like, but it does work.

As a side note, I think the UNION approach would work, but AFAIK SQL Server only allows ORDER BY on the last SELECT, and that ORDER BY applies to the entire result set (this post also states the same thing).

DECLARE @tags AS TABLE(TagID INT, Name VARCHAR(30))
INSERT INTO @tags VALUES(1, 'a')
INSERT INTO @tags VALUES(2, 'b')
INSERT INTO @tags VALUES(3, 'c')
INSERT INTO @tags VALUES(4, 'd')
INSERT INTO @tags VALUES(5, 'e')
INSERT INTO @tags VALUES(6, 'f')
INSERT INTO @tags VALUES(7, 'g')
INSERT INTO @tags VALUES(8, 'h')
INSERT INTO @tags VALUES(9, 'i')
INSERT INTO @tags VALUES(10, 'j')

DECLARE @selectedTags AS TABLE(TagID INT)
INSERT INTO @selectedTags
SELECT TOP 2 TagID FROM @tags WHERE Name < 'e' ORDER BY Name DESC
INSERT INTO @selectedTags
SELECT TOP 2 TagID FROM @tags WHERE Name >= 'e' ORDER BY Name

SELECT * 
FROM @tags T
JOIN @selectedTags ST ON ST.TagID = T.TagID
ORDER BY T.Name
like image 52
rsbarro Avatar answered Jan 14 '23 19:01

rsbarro