这是您的查询,格式为(至少)我可以阅读:
SELECT my_users.name, my_users.avatar, my_users.surname, fastmap_projects.*,
(SELECT COUNT(*)
FROM `fastmap_rating`
WHERE `fastmap_rating`.`map_id`=`fastmap_projects`.`id` AND `rate`='1') as `posivote`,
(SELECT COUNT(*)
FROM `fastmap_rating`
WHERE `fastmap_rating`.`map_id`=`fastmap_projects`.`id` AND `rate`='-1') as `negavote`
FROM `fastmap_projects` LEFT JOIN
`my_users`
ON `fastmap_projects`.`user_id`=`my_users`.`id`
WHERE `area_id` = '4' AND (`negavote` BETWEEN -3 AND 3) OR (`posivote` BETWEEN -3 AND 3)
您正在尝试在where
子句中使用列别名,而 SQL 不允许这样做(这是标准的一部分,而不是 MySQL 限制)。正常的解决方案是使用子查询或 CTE。但是,MySQL 有一个扩展。您可以使用having
子句代替where
子句:
SELECT my_users.name, my_users.avatar, my_users.surname, fastmap_projects.*,
(SELECT COUNT(*)
FROM `fastmap_rating`
WHERE `fastmap_rating`.`map_id`=`fastmap_projects`.`id` AND `rate`='1') as `posivote`,
(SELECT COUNT(*)
FROM `fastmap_rating`
WHERE `fastmap_rating`.`map_id`=`fastmap_projects`.`id` AND `rate`='-1') as `negavote`
FROM `fastmap_projects` LEFT JOIN
`my_users`
ON `fastmap_projects`.`user_id`=`my_users`.`id`
HAVING `area_id` = '4' AND (`negavote` BETWEEN -3 AND 3) OR (`posivote` BETWEEN -3 AND 3);
注意:只需检查括号以确保这是您想要做的。这将选择没有 id 的区域4
。你可能是这个意思:
HAVING `area_id` = '4' AND (`negavote` BETWEEN -3 AND 3 OR `posivote` BETWEEN -3 AND 3);