Pierro06
Pierro06

Reputation: 1

Given a string, find a row with whose value the string starts

I got a variable in bash, for exemple test=CCA123.

Assume I have a table named init with a column name in my MySQL database. The table contains the following values.

name:

Given this, I want an SQL that would select CC.

So, I want something like this:

mysql -u USER -pPASS -D DATABASE -e "SELECT name FROM intit WHERE $test LIKE name%`

But of course, that doesn't work! Any idea of how can i do that?

Upvotes: 0

Views: 31

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269633

I think this is the expression you want:

select name
from init
where '$test' like concat('test=', name, '%');

Alternatively, if you wanted to use an index and name is always two or three characters:

select name
from init
where name = left(substring_index('$test', '=', -1), 2) or
      name = left(substring_index('$test', '=', -1), 3);

Upvotes: 0

Guido
Guido

Reputation: 926

How about

"SELECT name FROM intit WHERE name LIKE \"$test%\""

Upvotes: 2

Related Questions