I have a following sample table structure
| Name | Address |
|---|---|
| Name1 | Address1 |
| Name2 | Address2 |
I need to get the Name1 but my search criteria is longer than the column value.
Sample query
SELECT *
FROM SampleTable
WHERE Name = 'Name1Me'
I have tried truncating the search criteria until I get a match like below
SELECT *
FROM SampleTable
WHERE Name = 'Name1Me'
if no result then
SELECT *
FROM SampleTable
WHERE Name = 'Name1M'
if no result then
SELECT *
FROM SampleTable
WHERE Name = 'Name1M'
Result okay
But this will make a lot of queries if the search criteria is much longer than the column value.
I’m asking if there’s a better query for situations like this.
Edit:
I’m using MariaDB 10.3 on a Raspberry Pi 3B+.
By better, I mean if there’s a single query for this or if it’s possible to do this in less queries.
>Solution :
You can use something like this – reducing the right operand to the length of the left operand:
SELECT *
FROM SampleTable
WHERE Name = left('Name1Me',char_length(Name))
But beware:
- The actual string functions to use may change depending on the database vendor (you have not tagged), and/or if you use some international character sets.
- You need to make sure that the length of the search criteria and the length of the column value do not result in invalid function calls (zero length strings, for example).