当前位置: 动力学知识库 > 问答 > 编程问答 >

reversing SQL wildcard direction

问题描述:

When comparing a string to entries in the database, the _ or % wildcards allow you to search for strings in the database that contain the searchterm. But can you reverse this, such that you look for database entries that are contained within the search term?

i.e.

SELECT Species FROM Animal WHERE Species LIKE 'horse_'

returns: horse, horses

how would you modify this to return both values if your original term was "horses" rather than "horse"?

SELECT Species FROM Animal WHERE Species_ LIKE 'horses'

-> invalid sql syntax

网友答案:

You can swap the two values, so Species is the part after LIKE. Also, the wildcard pattern is a string value. If you want to add a wildcard, add it as a string value. That means using a function like CONCAT or maybe the || or & operator, depending on the database you use:

To match (only) 'horse':

SELECT Species FROM Animal WHERE 'horses' like CONCAT(Species, '_')

Side note: in this case, you have a wildcard for a single character, and this character always matches the 's' in 'horses'. So essentially, the query above would be the same as:

SELECT Species FROM Animal WHERE Species = 'horse'
分享给朋友:
您可能感兴趣的文章:
随机阅读: