SQL中的WHERE子句失败

时间:2016-07-29 11:22:11

标签: mysql

我有以下SQL:

SELECT `id`,`postcode`,
(SELECT COUNT(*) FROM `kids` WHERE `kids`.`bookingID` = `booking`.`id`) AS `k`,
(SELECT COUNT(*) FROM `youth` WHERE `youth`.`bookingID` = `booking`.`id`) AS `y`
FROM `booking`
WHERE `k` > 0 AND `y` > 0

但由于列k未知,它失败了。虽然它不是数据库中的真正列,但我在SELECT中定义了它,那么我哪里出错?

2 个答案:

答案 0 :(得分:2)

您无法引用SELECT子句中WHERE中定义的别名。一般而言,这不仅适用于MySQL,而且只适用于MySQL。

MySQL提供了扩展程序。在这种情况下,您可以使用HAVING子句来实现此目的:

SELECT `id`,`postcode`,
       (SELECT COUNT(*) FROM `kids` WHERE `kids`.`bookingID` = `booking`.`id`) AS `k`,
       (SELECT COUNT(*) FROM `youth` WHERE `youth`.`bookingID` = `booking`.`id`) AS `y`
FROM `booking`
HAVING `k` > 0 AND `y` > 0;

答案 1 :(得分:1)

如果你使用count(),我认为你必须在这个sql中使用。