Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL search multiple values in same field

Tags:

search

mysql

I'm building a simple search algorithm and I want to break my string with spaces, and search my database on it, like so:

$search = "Sony TV with FullHD support";   $search = explode( ' ', $search );  SELECT name FROM Products WHERE name LIKE %$search[1]% AND name LIKE %$search[2]% LIMIT 6 

Is this possible?

like image 829
Nir Tzezana Avatar asked Apr 26 '13 15:04

Nir Tzezana


People also ask

How do I find multiple values in one column in SQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);

How do I find multiple values in SQL?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

How do I filter multiple values in one column in SQL?

Show activity on this post. ID | Name | Filter1 | Filter2 | Filter3 | Filter4 ... and so on... select Name from tblABC where Filter1=1 and Filter2 = 7 and Filter3 = 33 ... and so on...'


2 Answers

Yes, you can use SQL IN operator to search multiple absolute values:

SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... ); 

If you want to use LIKE you will need to use OR instead:

SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2'; 

Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.

like image 61
Glitch Desire Avatar answered Sep 24 '22 22:09

Glitch Desire


Try this

Using UNION

$sql = ''; $count = 0; foreach($search as $text) {   if($count > 0)      $sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";   else      $sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";    $count++; } 

Using WHERE IN

$comma_separated = "('" . implode("','", $search) . "')";  // ('1','2','3') $sql = "Select name From myTable WHERE name IN ".$comma_separated ; 
like image 40
codingbiz Avatar answered Sep 24 '22 22:09

codingbiz