0

Is it possible, to get matched string part in sql statement, which has many like statements.

SELECT fieldname
FROM table
WHERE content LIKE '%$val_1%'
   OR content LIKE '%$val_2%'
   OR content LIKE '%$val_3%'
   .
   .
   .
   OR content LIKE '%$val_n%'

i.e i need to get all that values($val_1, or(and) $val_2 ...), which matched in content.

example

if my content is the following

content = 'this is my testing text'

and i have the following values, to check in like statements

$val_1 = 'thi';
$val_2 = 'esting';
$val_3 = 'other value, which not in my content';

I need to get the matched partts, i.e "thi" and "esting", because they are matched in my content.

5
  • 1
    I don't get your question.....your query will run, if that is what you are asking Commented Jan 30, 2012 at 20:44
  • It sounds like you want to match the pattern val_[0-9]? If that's so, take a look at: dev.mysql.com/doc/refman/5.0/en/pattern-matching.html - RLIKE is probably what you are after. Commented Jan 30, 2012 at 20:47
  • I need to get one of ($val_1,...$val_n) values(or some of them), which cause my query to run. i.e that values, which are in my content. Commented Jan 30, 2012 at 20:47
  • Are you asking how to find which $val_* was matched in content? Commented Jan 30, 2012 at 20:48
  • I believe that @Syom is asking how to get which like operator(s) resulted in the match. For example, did "content LIKE '%$val_1%'" evaluate to true? or did "content LIKE '%$val_2%'"? etc. Commented Jan 30, 2012 at 20:49

3 Answers 3

2

Since you say you're doing this in PHP, just use PHP to find out which bits matched after you get your rows back:

if (stripos($row['content'], $val_1) !== false) this bit matched!
if (stripos($row['content'], $val_2) !== false) this bit matched!
if (stripos($row['content'], $val_3) !== false) this bit matched!
Sign up to request clarification or add additional context in comments.

1 Comment

stripos() would be more appropriate
1
SELECT fieldname, matchpart = '$val_1'
FROM table
WHERE content LIKE '%$val_1%'
UNION 
SELECT fieldname, matchpart = '$val_2'
FROM table
WHERE content LIKE '%$val_2%'
...
UNION 
SELECT fieldname, matchpart = '$val_n'
FROM table
WHERE content LIKE '%$val_n%'

Comments

1

The following query will return the column fieldname and condX where condX == 1 iff content LIKE '%$val_X%', else 0.

Originally from https://stackoverflow.com/a/2261001/961455:

SELECT fieldname,
    `content` LIKE '%$val_1%' AS cond1,
    `content` LIKE '%$val_2%' AS cond2,
    ... ,
   `content` LIKE '%$val_n%' AS condn
FROM table
HAVING cond1 OR cond2 OR ... OR condn

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.