MySql ORDER由rand()一行

时间:2016-10-25 17:49:13

标签: php mysql

我有这个PHP代码

$coma_count=substr_count($Hob,',');
        if ($coma_count==0) {
            $query="SELECT * FROM user_opt WHERE Interests='$Hob' LIMIT 80";
        }else{
            $expl=explode(',',$Hob);
            for ($i=0; $i <=$coma_count; $i++) { 
                    $query.=" UNION SELECT * FROM users WHERE Interests LIKE '%{$expl[$i]}%'";      
            }
}
    $sql=$con->query($query." ORDER BY RAND()") or die($con->error);

$coma_count的数量从0到112不等,问题是$coma_count为0时(表示只选择了国家/地区)我的查询看起来像SELECT * FROM user_opt WHERE Country='$Countr' LIMIT 80 ORDER BY RAND()这不是SQL接受了。我该怎么办?

1 个答案:

答案 0 :(得分:1)

创建一个$limit变量,如果需要,设置它,然后追加它:

$limit = '';
$coma_count=substr_count($Hob,',');
    if ($coma_count==0) {
        $query="SELECT * FROM user_opt WHERE Interests='$Hob'";
        $limit = " LIMIT 80";
    }else{
        $expl=explode(',',$Hob);
        for ($i=0; $i <=$coma_count; $i++) { 
                $query.=" UNION SELECT * FROM users WHERE Interests LIKE '%{$expl[$i]}%'";      
        }
}
$sql=$con->query($query." ORDER BY RAND()".$limit) or die($con->error);