0

为什么我在“where 子句”中得到未知列“negavote”

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)

你能提示我如何改变它来工作吗?

4

2 回答 2

2

这是您的查询,格式为(至少)我可以阅读:

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);
于 2014-11-22T15:35:30.277 回答
0

您不能在 SQL where 子句中使用列别名(PostgreSQL 除外,因为那家伙很流畅)

重复子选择或将查询包装在子查询中并将过滤器应用于上层查询

SELECT 
    *
FROM (
  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)
于 2014-11-22T15:39:51.370 回答