0

我正在尝试使用基于标量子查询结果的 WHERE 子句。查询在没有 WHERE 子句的情况下正确执行。使用 WHERE 子句,我得到错误代码:1054。“where 子句”中的未知列“available_services”。

如何实现基于子查询结果的过滤?

此外,由于子查询可能非常低效,因此有关如何改进查询的任何建议都会很有用。

SELECT DISTINCT 
    `suppliers`.`id` AS `supplier_id`, 
    `suppliers`.`name`, 
    `suppliers`.`code`, 
    `suppliers`.`notes`, 
    (
        SELECT GROUP_CONCAT(
            `services`.`name` 
            ORDER BY `services`.`order` 
            SEPARATOR ', '
        ) 
        FROM `supplier_services` 
        LEFT JOIN `services` 
            ON `supplier_services`.`service_id` = `services`.`id` 
        WHERE 
            `supplier_services`.`service_id` = `services`.`id`
            AND `supplier_services`.`supplier_id` = `suppliers`.`id`
        GROUP BY `supplier_services`.`supplier_id`
    ) AS `available_services`
FROM `suppliers` 
WHERE `available_services` like '%pet%' 
GROUP BY `suppliers`.`id`
4

2 回答 2

0

嗨,如果您想获得子查询结果,您应该在查询中作为变量

SELECT DISTINCT 
`suppliers`.`id` AS `supplier_id`, 
`suppliers`.`name`, 
`suppliers`.`code`, 
`suppliers`.`notes`, 
@available_services := (
    SELECT GROUP_CONCAT(
        `services`.`name` 
        ORDER BY `services`.`order` 
        SEPARATOR ', '
    ) 
    FROM `supplier_services` 
    LEFT JOIN `services` 
        ON `supplier_services`.`service_id` = `services`.`id` 
    WHERE 
        `supplier_services`.`service_id` = `services`.`id`
        AND `supplier_services`.`supplier_id` = `suppliers`.`id`
    GROUP BY `supplier_services`.`supplier_id`
) AS `available_services_as_column_view`
FROM `suppliers` 
WHERE @available_services like '%pet%' 
GROUP BY `suppliers`.`id`
于 2019-11-14T16:18:55.563 回答
0

如果有人遇到此问题并遇到类似问题,原因(正如 Nico 在评论中指出的那样)是虽然您可以在 where 子句中使用表别名,但您不能使用字段别名。但是,您可以在 HAVING 子句中使用字段别名。

解决方案是使用

GROUP BY `suppliers`.`id` 
HAVING `available_services` like '%pet%'

代替

WHERE `available_services` like '%pet%'  
GROUP BY `suppliers`.`id`

或者,where 子句中的别名可以再次用子查询替换,但这可能效率低下,或者它可能被 mysql 缓存并且不是问题,如果您使用该解决方案,则需要仔细检查。

于 2019-11-14T16:57:00.737 回答