MYSQL喜欢但不相等

时间:2016-07-06 17:06:19

标签: php mysql

我有这个结构的数据库

Id      Country         Interests
12      Azerbaijan      Acting,Reading
14      Azerbaijan      Reading,Writing
16      Azerbaijan      Acting,sleeping

这个PHP / MYSQL

$Interests = "Acting,Reading";

$Country = "Azerbaijan";
$query = "SELECT * FROM user_opt WHERE Country='$country' AND Interests='$Interests' ";
$i = substr_count($Interests,',');
for($j = 0; $j <= $i; $j++) {
   $a = explode(',', $Interests);
   $query2 = "SELECT * FROM user_opt WHERE Country='$country' AND Interests LIKE '%{$a[$j]}%'";
}

因此,使用此代码,它会返回此ID

12
12
16
12
14

但我希望它能够回归 12 16 14

4 个答案:

答案 0 :(得分:0)

您可能希望使用OR来查找您的所有兴趣。为此,首先构建OR语句,然后将其插入查询中。注意:这不是一种安全/首选方式!确保你正在使用PDO或mysqli并绑定你的参数!

$interestArr = [];
foreach($Interests as $Interest) {
    $interestArr[] = "Interests LIKE '%{$Interest}%'";
}

$query2 = "SELECT * FROM user_opt WHERE Country='$country' AND (".implode(' OR ',$interestArr).")";

答案 1 :(得分:0)

你可以使用正则表达式来避免循环

SELECT distinct *  
FROM user_opt 
WHERE Country='$country' AND Interests REGEXP 'Acting|Reading';

答案 2 :(得分:0)

我是用

做的
!=

喜欢这个

$query2=$con->query("SELECT * FROM user_opt WHERE Country='$country' AND Interests!='$Interests' AND Interests LIKE '%{$a[$j]}%'") or die($con->error);

答案 3 :(得分:0)

你不需要循环结果,只需使用OR比较器

$Interests = "Acting,Reading";

$Country = "Azerbaijan";
$query = "SELECT * FROM user_opt WHERE Country='$country' AND ("     
$a = explode(",", $Interests);
$interestQuery = "";
for($j = 0; $j < count($a); $j++) {
    if($j+1 == count($a))
        $interestQuery = $interestQuery . "Interests LIKE '%". $a[$j] ."%') "
    else
        $interestQuery = $interestQuery . "Interests LIKE '%". $a[$j] ."%' OR" 
}
$query = $query.$interestQuery;
$echo $query;