0

该死的对我的 MYSQL 查询的语法感到困惑。

这是正确的吗?在互联网上找不到类似的条目。

$query_game_string = '';

while($game = mysql_fetch_assoc($get_game_list)){
    $query_game_string .= ' OR target = "' . $game['id'] . '" AND ancestors = "0"';   
}

echo '' . $query_game_string . '';  

//prints: OR target = "11" AND ancestors = "0" OR target = "12" AND ancestors = "0" OR target = "27" AND ancestors = "0" OR target = "29" AND ancestors = "0" OR target = "32" AND ancestors = "0"


        $database->connect(); 

            $comments = mysql_query(
                'SELECT * 
                    FROM ' . $database->db_prefix . 'comments 
                        WHERE user_id = "' . $user->user_object["id"] . '"' .
                        $query_game_string . '                                    
                        ORDER BY created DESC'
            , $database->connection_handle);                     

        $database->close();

所以实际的查询总共是:

'SELECT * 
    FROM ' . $database->db_prefix . 'comments 
        WHERE user_id = "' . $user->user_object["id"] . '"' .
        'OR target = "11" AND ancestors = "0" OR target = "12" AND ancestors = "0" OR target = "27" AND ancestors = "0" OR target = "29" AND ancestors = "0" OR target = "32" AND ancestors = "0"' . '                                    
        ORDER BY created DESC'

语法好吗?

4

1 回答 1

0

不知道你在找什么,但可能你需要括号:

OR (target = "11" AND ancestors = "0")
OR (target = "12" AND ancestors = "0")
OR (target = "27" AND ancestors = "0")
OR (target = "29" AND ancestors = "0")
OR (target = "32" AND ancestors = "0")

php 来实现:

while($game = mysql_fetch_assoc($get_game_list))
{
    $query_game_string .= ' OR (target = "' . $game['id'] . '" AND ancestors = "0")';   
}

一种简化查询的方法是使用IN操作数

 OR target IN("11","12","27","29","32") AND ancestors = "0"

php:

$targets = array();
while($game = mysql_fetch_assoc($get_game_list))
{
    $targets[] = '"'.$game['id'].'"';   
}
$query_game_string = ' OR target IN (' . implode(",",$targets) . ') AND ancestors = "0"';
于 2012-06-06T20:59:18.927 回答