Search muliple values from a comma separated column in mysql
-
21-12-2019 - |
Domanda
I don't think it is worth to try for a solution with multiple OR conditions using FIND_IN_SET()
where myColumn
might contain data as 1,2,3
or 2,3,6..
in random
FIND_IN_SET( '1', myColumn ) OR FIND_IN_SET( '3', myColumn ) OR FIND_IN_SET( '5', myColumn )
If this is not the right one, I might require a normalised solution to suit my query
Soluzione
Normalise you database if possible, but if you are desperate you could do something like this:-
SELECT DISTINCT Sometable.*
FROM SomeTable
INNER JOIN
(
SELECT 1 AS i UNION SELECT 2 UNION SELECT 3
) Sub1
WHERE FIND_IN_SET(Sub1.i, Sometable.myColumn)
EDIT - using an array of keys without a loop
<?php
$some_keys = array(1,2,3);
$sql = "SELECT DISTINCT Sometable.*
FROM SomeTable
INNER JOIN
(
SELECT ".implode(" AS i UNION SELECT ", $some_keys)." AS i
) Sub1
WHERE FIND_IN_SET(Sub1.i, Sometable.myColumn)";
?>
Or if the values apply to the key of another table then you can use that:-
<?php
$some_keys = array(1,2,3);
$sql = "SELECT DISTINCT Sometable.*
FROM SomeTable
INNER JOIN SomeOtherTable
ON SomeOtherTable.id IN (".implode(",", $some_keys).")
AND FIND_IN_SET(SomeOtherTable.id, Sometable.myColumn)";
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow