1

What is the proper way of doing the following in a mysql query?:

$string="apple banana orange";

mysql column A = "banana"

mysql query: column A not included in $string

Thanks!

2
  • What are you trying to do? Commented Mar 21, 2013 at 20:32
  • Thanks all! Let me try to clarify. I have a string $string="apple banana orange"; How can I do a mysql query where: a) column A IS included in $string b) column A IS NOT included in $string. Ex mysql_query("select * from DB where [A IS NOT included in $string]"); Commented Mar 21, 2013 at 22:15

3 Answers 3

2

If each row has a column called A that has space separated tokens you can run this:

SELECT * FROM table_name
WHERE LOCATE(CONCAT(' ',A,' '),'apple banana orange') = 0;

The reason I padded a blank on both sides would be to cover a situation like this:

SELECT * FROM table_name
WHERE LOCATE(CONCAT(' ',A,' '),'pineapple banana orange') = 0;

As a character string

  • apple is in apple banana orange
  • apple is in pineapple banana orange

In terms of semantics

  • apple is in apple banana orange
  • apple is not in pineapple banana orange

What if you were looking for grape ?

As a character string

  • grape is in apple banana orange grape
  • grape is in apple banana orange grapefruit

In terms of semantics

  • grape is in apple banana orange grape
  • grape is not in apple banana orange grapefruit

Give it a Try !!!

CAVEAT

The query itself would yield a full table scan.

You should look into doing FULLTEXT indexes.

Sign up to request clarification or add additional context in comments.

Comments

0
SELECT * FROM table_name 
WHERE A NOT IN ('apple', 'banana', 'orange');

Comments

0

Maybe something like this? (I have not tested it though but I think it would work)

<?php
$string = "apple banana orange";

//Make an array of each fruit in string (with delimiter space)
$items = explode(" " , $string);

//None of the fruits in $string would be listed in resultset
$query = "SELECT * FROM fruits WHERE columnA NOT IN ($items)";
//db-handling...
?>

UPDATE: Don't make an array... ..do this instead...! $items = str_replace(" ", ",", $string);

2 Comments

A PHP array cannot be placed into a query's IN () clause.
Of course! You're right! $items could be using str_replace() - replacing spaces with comma in $string.

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.