为什么我得到 未知专栏' negavote'在' 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`
WHERE
`area_id` = '4'
AND (`negavote` BETWEEN -3 AND 3)
OR (`posivote` BETWEEN -3 AND 3)
您能否提示如何更改此功能?
答案 0 :(得分:1)
这是您的查询,格式化(至少)我可以阅读:
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);
作为备注:只需检查您的括号,确保这是您想要做的。这将选择没有身份4
的区域。你可能是这个意思:
HAVING `area_id` = '4' AND (`negavote` BETWEEN -3 AND 3 OR `posivote` BETWEEN -3 AND 3);
答案 1 :(得分: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)