上帝该死我对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'
语法还可以吗?
答案 0 :(得分: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"';