我有一个MySQL声明来帮助找到推荐列表的类似频段。它做我想要的,但一件小事。它不会阻止已经被查询的乐队。
以下是声明:
foreach ($recomBands as $val) {
$genres[] = "'%".$val."%'";
}
$string = implode(' OR `genre` LIKE ', $genres);
foreach ($favedBands as $value) {
$bands[] = "'" . sanitize($value) . "'";
}
$bandString = implode(' OR `band_name` != ', $bands);
$sql = "SELECT `band_name`, `band_id` FROM `song_genres` WHERE `band_name` != {$bandString} AND `genre` LIKE {$string}";
// QUERY CODE AND WHAT NOT GOES HERE. ALL WORKING FINE
那回声:
SELECT `band_name`, `band_id` FROM `song_genres` WHERE `band_name` != 'Bears and Company' AND `genre` LIKE '%Indie Rock%' OR `genre` LIKE '%Progressive Rock%' OR `genre` LIKE '%Alternative Rock%' OR `genre` LIKE '%Indie Folk%'
这是一个有效的查询(虽然不是大多数人会完全做的,但这不是重点)。输出数组显示
array(17) {
[0]=>
string(20) "Henry's Funeral Shoe"
[1]=>
string(17) "Bears and Company"
[2]=>
string(17) "Bears and Company"
// AND A LIKE 15 MORE OF BEARS AND COMPANY
目标是比较一个乐队中发现的所有类型,并将它们分组到其他类型的乐队,然后对它们进行排序。一切正常,但我想从查询中出现的乐队仍然出现。为什么呢?
P.S。我有其他虚拟账号用于随机顺序测试多个乐队,流派等。
答案 0 :(得分:0)
SQL中的不等于<>
。
所以改为
$bandString = implode(' OR `band_name` <> ', $bands);
此外,您必须()
发表OR
声明
SELECT `band_name`, `band_id`
FROM `song_genres`
WHERE `band_name` != 'Bears and Company' AND (`genre` LIKE '%Indie Rock%' OR `genre` LIKE '%Progressive Rock%' OR `genre` LIKE '%Alternative Rock%' OR `genre` LIKE '%Indie Folk%')
使用预备语句。它更安全,更易读。
答案 1 :(得分:0)
我最终尝试了所有的建议,但没有一个有效。但我改变了:
$bandString = implode(' OR `band_name` != ', $bands);
到此:
$bandString = implode(' AND `band_name` != ', $bands);
显然OR条件导致条件跳过所有值。在撰写声明时,我根本没有注意。