左连接的where子句中的Mysql查询错误
Posted
技术标签:
【中文标题】左连接的where子句中的Mysql查询错误【英文标题】:Mysql Query error in where clause on left join 【发布时间】:2015-08-01 14:54:25 【问题描述】:对不起,基本问题:
select `plans`.`name`, `A`.`subscription_id`, `A`.`amount`,
`A`.`created_date`, `A`.`end_date`,
`A`.`subscription_status`, `users`.`email`, `A`.`plan_id`,
`A`.`user_id`, `usage`.`created_at` as `usagedate`,
COUNT(usage.id) as used_count
from `subscriptions` A
left join `users` on `users`.`id` = `A`.`user_id`
left join `plans` on `A`.`plan_id` = `plans`.`Id`
left join `usage` on `A`.`user_id` = `usage`.`user_id`
where `usage`.`created_at` between A.created_at and A.end_date
group by `A`.`plan_id`
我收到了错误
1054 - “where 子句”中的未知列“A.created_at”
【问题讨论】:
确定订阅表中有 created_at 列? 在select
,你有A.created_date
。
对愚蠢的错误和问题感到抱歉。否决票 :(
更重要的是,您的查询还有其他一些问题。 1) 将 WHERE 条件移动到 ON 子句以获得真正的 LEFT JOIN。现在它作为常规内部连接执行。 2) 您错过了在 GROUP BY 中指定几列。 (mysql 并不挑剔,我知道...)
@jarlh 感谢您的积分。我会改正的。
【参考方案1】:
我认为应该有A.created_date
而不是A.created_at
select `plans`.`name`, `A`.`subscription_id`, `A`.`amount`,
`A`.`created_date`, `A`.`end_date`,
`A`.`subscription_status`, `users`.`email`, `A`.`plan_id`,
`A`.`user_id`, `usage`.`created_at` as `usagedate`, COUNT(usage.id) as
used_count from `subscriptions` A
left join `users` on `users`.`id` = `A`.`user_id`
left join `plans` on `A`.`plan_id` = `plans`.`Id`
left join `usage` on `A`.`user_id` = `usage`.`user_id`
where
`usage`.`created_at` between A.created_date and A.end_date
group by
`A`.`plan_id`
【讨论】:
【参考方案2】:我想它应该是a.created_date
SELECT `p`.`name`, `A`.`subscription_id`, `A`.`amount`, `A`.`created_date`, `A`.`end_date`, `A`.`subscription_status`, `u`.`email`, `A`.`plan_id`, `A`.`user_id`, `us`.`created_at` AS `usagedate`, COUNT(`us`.`id`) AS `used_count`
FROM `subscriptions` A
LEFT JOIN `users` u on `u`.`id` = `A`.`user_id`
LEFT JOIN `plans` p on `A`.`plan_id` = `p`.`Id`
LEFT JOIN `usage` us on `A`.`user_id` = `us`.`user_id`
WHERE `us`.`created_at` between `A`.`created_date` and `A`.`end_date`
GROUP BY `A`.`plan_id`
【讨论】:
以上是关于左连接的where子句中的Mysql查询错误的主要内容,如果未能解决你的问题,请参考以下文章
SQL左连接与JOIN条件中的过滤器与WHERE子句中的过滤器[重复]