我有以下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
中定义了它,那么我哪里出错?
答案 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中使用。