SQL - Where criteria to find names between A-F

淺唱寂寞╮ 提交于 2020-01-23 00:30:14

问题


Simple question:

I need a solution so that I can find, lets say names, between A-F, INCLUDING all names that start with F.

If you use BETWEEN or A >= value <= F you find out that it stops at F. So I am posting this for suggestions.

NOTE: User will see 2 textboxes that accept a range user can type. The user refines how far to go in F boundary as such: User types in 'Fa' means the result should return: Fauder, Fail, Famber, ... etc

I have currently 2 solutions but there's got a be a better way.

Solution 1: This will add 1 to outer boundary but may include result if there's a name that is single 'G', highly unlikely though. WHERE name >= 'A' AND <= CHAR(ASCII('F') + 1)

Solution 2: This solution appends last letter of alphabet field length times. WHERE name >= 'A' AND <= 'FZZZZZZZZZZZZZZZZZZZZZ'

Although the above solutions are workable, my search can be refined as such: A to Fs (should give me everything from A to and including Fs....). With this solution #1 is broken since it works with single ascii.

Suggestions are welcome.


回答1:


In a comment you expand the requirement to include A - Fxxx.

SET @start = 'A'
SET @end   = 'Fxxx'

SELECT
  *
FROM
  table
WHERE
  (name >= @start AND name < @end)
  OR (name LIKE @end + '%')

Note that this does not include functions on the name field; such functions prevent range seeks on indexes. However, the inclusion of the OR degrades the index seek too. Although it's extra code, this actually can be more performant is some cases...

SELECT
  *
FROM
  table
WHERE
  (name >= @start AND name < @end)

UNION ALL

SELECT
  *
FROM
  table
WHERE
  (name LIKE @end + '%')


EDIT

In hindsight, your Solution 2, although you don't like it, is probably the best.

Turning Fxxx to FxxxZZZZZZZZZZ is simple enough with STUFF(), provided that you know the max string length, which you should do as the database is yours.

It doesn't have any functions on the name field, and it doesn't use an OR in the WHERE clause. Which means that you get a pure range seek on any index.

Performance wise, I do not think you can improve on this.




回答2:


You can do:

WHERE name >= 'A' AND name < 'G'



回答3:


How about this?

WHERE SUBSTR(name, 1, 1) >= 'A' AND SUBSTR(name, 1, 1) <= 'F'



回答4:


Will this work for you:

select * 
from MyTable
where left(name, 1) between 'a' and 'f'



回答5:


How much more simple can you make it?

WHERE NAME LIKE '[a-f]%'


来源:https://stackoverflow.com/questions/9893329/sql-where-criteria-to-find-names-between-a-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!