简体   繁体   中英

SQL Exclude 'The ' from the beginning of a search result

I am trying to exclude 'A ' and 'The ' from the beginning of values in a column. I am searching for artist starting with the letter 'A' like:

 AND artist LIKE LOWER('A%') AND artist NOT LIKE LOWER('A %')

Problem is this will give me artists starting with 'A%', and not giving me artists start with 'A %', but it will also exclude artists starting with 'AA%'

If some band decided to name themselves 'A Apple', they would be excluded from my search. How could i do this query without excluding 'AA%'

Thanks in Advance! Jay

AND artist LIKE ('A%')
AND (artist NOT LIKE LOWER('A %') OR artist LIKE ('A A%'))

I hope this is for a hobby or small db, because the LIKE statement won't be very friendly to performance.

This is a common and cumbersome problem, often solved by having a second field which contains the artist name in the form "Rolling Stones, The" alongside the displayed name "The Rolling Stones". Searches are performed against the former, but results displayed using the latter.

But if you're stuck with the data you've got, you need something like:

AND UPPER(artist) LIKE 'A%'
AND ( UPPER(artist) LIKE 'A A%' OR NOT (UPPER(artist) LIKE 'A %') )

If you have control over the database structure, and particularly if this is a large database, it may be more beneficial to simply add a "SearchArtist" column which contains the artist's name as it would appear in searches or be used for sorting. This way you could display the full name but sort by the searchable name:

select artist form table order by searchArtist;

That way The Rolling Stones would appear in the list ahead of Steppenwolf...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM