我有一个这样的表:
product_id attribute_id
2 7,8
1 2,7
3 7
我还有一个名为 $search_ids
的变量,其中包含要搜索的值。
如果 $search_ids
的值为 7
,我希望它返回所有 3 行,但如果它的值为 2,7
或 7,8
然后我只想返回该行。
我尝试了以下操作,其中 $search_ids
的值为 7,但这不会返回第二行!如果我将行的值从 2,7
更改为 7,2
那么它也会返回该行!
现在执行以下查询:
$q = "SELECT product_id FROM product_attributes
WHERE attribute_id IN ('$search_ids')
OR attribute_id IN ($search_ids)
返回
2
3
而不是
2
1
3
最佳答案
我会这样做:
$search_ids = '2,7'; //dummy data
$q = '';
$ids = explode(',', $search_ids);
foreach ($ids as $id) {
$q .= (strlen($q) == 0)?'':' AND';
$q .= ' FIND_IN_SET(\''.$id.'\', attribute_id) > 0';
}
$q = 'SELECT product_id FROM product_attributes WHERE' . $q;
关于php - 返回部分匹配和完全匹配时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22428277/