MySQL无法在WHERE语句中使用Alias?

时间:2013-11-26 09:12:20

标签: mysql

SELECT MIN(deals_bookings.date) as booking_date, `users`.`company_cvrnr`, `users`.`company_debnr`, `refnumbers`.`refno` 
FROM `refnumbers` 
JOIN `deals` ON (`refnumbers`.`deal_id` = `deals`.`ID`)
JOIN `users` ON (`users`.`id` = `deals`.`partner_id`) 
LEFT JOIN deals_bookings ON (deals_bookings.deal_id = deals.ID)
WHERE `refnumbers`.`is_claimed` = '1'
AND booking_date >= '2013-11-21'
AND `refnumbers`.`claimed_at` BETWEEN '2013-11-26 00:00:00' AND '2013-11-26 23:59:59' 
GROUP by refno
ORDER BY `refnumbers`.`claimed_at` DESC

这是我尝试执行的查询。当我有行

时会出现问题
AND booking_date >= '2013-11-21'

我收到错误未知列。我做错了什么?

使用MIN(deals_bookings.date)我试图获得具有最低日期的deals_bookings中的行和“日期”列。

2 个答案:

答案 0 :(得分:4)

试试这个...

问题是WHERE子句在SELECT语句之前执行。因此,booking_date列尚不可用。 HAVING子句在SELECT语句之后执行。选择完所有内容后,它会过滤掉各种结果。

SELECT MIN(deals_bookings.date) as booking_date, `users`.`company_cvrnr`, `users`.`company_debnr`, `refnumbers`.`refno` 
FROM `refnumbers` 
JOIN `deals` ON (`refnumbers`.`deal_id` = `deals`.`ID`)
JOIN `users` ON (`users`.`id` = `deals`.`partner_id`) 
LEFT JOIN deals_bookings ON (deals_bookings.deal_id = deals.ID)
WHERE `refnumbers`.`is_claimed` = '1'
AND `refnumbers`.`claimed_at` BETWEEN '2013-11-26 00:00:00' AND '2013-11-26 23:59:59' 
GROUP by refno
HAVING MIN(deals_bookings.date) >= '2013-11-21'
ORDER BY `refnumbers`.`claimed_at` DESC

答案 1 :(得分:3)

添加having子句

SELECT MIN(deals_bookings.date) as booking_date, `users`.`company_cvrnr`, `users`.`company_debnr`, `refnumbers`.`refno` 
FROM `refnumbers` 
JOIN `deals` ON (`refnumbers`.`deal_id` = `deals`.`ID`)
JOIN `users` ON (`users`.`id` = `deals`.`partner_id`) 
LEFT JOIN deals_bookings ON (deals_bookings.deal_id = deals.ID)
WHERE `refnumbers`.`is_claimed` = '1'
AND `refnumbers`.`claimed_at` BETWEEN '2013-11-26 00:00:00' AND '2013-11-26 23:59:59' 
GROUP by refno
HAVING booking_date >= '2013-11-21'
ORDER BY `refnumbers`.`claimed_at` DESC

因为booking_date是汇总数据。