I have a numbers in database
88746
65654
78655
67856
09958
55640
I need to get out put when i search
'786' means search key is 786
search result
88746
78655
67856
The output criteria if it is any occurrence 7 8 6 in that number groups,means if i search 5 that is the search key is 5 then we need to show all rows with number 5 is occurred. example keyword is 5 out put is 65654,78655,67856,09958,55640 means the digit 5 occurred in all that set of numbers
I need a mysql query for this challenge
I tried a query
select * from plates where number LIKE %786%
--------
number |
------ |
88746 |
65654 |
78655 |
67856 |
09958 |
OUTPUT
number |
------ |
88746 |
78655 |
67856 |
You have to check for each individual character if it is in the larger number.
SELECT * FROM plates
WHERE number LIKE '%7%'
AND number LIKE '%8%'
AND number LIKE '%6%'
If your search input consists of more or less characters you have to change your query. What I suggest is you have some sort of template string "number like '%{$i}%'"
and use $i
top put the number into it and then append it to the existing query.
Example:
Search input is 8765.
$query = "SELECT * FROM plates WHERE ";
$pattern = "number LIKE '%%%s%%' ";
$input = "8765";
$c = strlen($input); // 8765 returns 4, 456 returns 3 etc.
for ($i = 0; $i < $c; $i++) {
$pattern2 = "";
$pattern2 = sprintf($pattern, $input[$i]);
if ($i < ($c - 1)) { // the last LIKE statement should not have AND
$pattern2 .= "AND ";
}
$query .= $pattern2;
}
echo $query // SELECT * FROM plates WHERE number LIKE '%8%' AND number LIKE '%7%' AND number LIKE '%6%' AND number LIKE '%5%'
First you need to split string,
$arr = str_split("786");
array_walk($arr, function (&$item) {
$item = '"%' . $item . '%"';
});
$in_clause = rtrim(implode(" OR ", $arr), 'OR ');
$query = "select * from plates where number $in_clause";
I hope this will help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.