MySQL无法访问子查询中的别名

时间:2013-04-03 15:16:08

标签: mysql

所以我有这个查询(不是用于生产用途,只是一个查询,无论性能如何,都可以从管理上获取数据)

SELECT 
  `guests`.`id`, 
   CONCAT(u.`fname`, '', u.`lname`) "name", 
  `u`.`id` "u", 
   (SELECT COUNT(r.id) FROM reservations r WHERE r.guest_id=guests.id) "reservations", 
   (SELECT COUNT(t.id) FROM tasks t WHERE t.guest_id = guests.id) "tasks", 
   (SELECT COUNT(m.id) FROM scheduled_emails m JOIN reservations r ON (r.guest_id = `guests`.`id` AND m.reservation_id = r.id)) "emails", 
  `guests`.`created` "created", 
  `guests`.`updated` "updated" 
FROM `guests`
JOIN `users` AS u ON u.`id` = `guests`.`user_id` LIMIT 0,25

我得到了

#1054 - Unknown column 'guests.id' in 'on clause'

引起问题的行是第3个子查询:

(SELECT COUNT(m.id) FROM scheduled_emails m JOIN reservations r ON (r.guest_id = `guests`.`id` AND m.reservation_id = r.id)) "emails", 

任何人都知道为什么会在这里失败?我的意思是我没有使用别名,guest是表的名称,它在2个第一个子查询中被读取正常。第三个子查询的区别在于它正在使用JOIN ...任何想法?感谢

2 个答案:

答案 0 :(得分:2)

直接

JOIN所有表,而不是使用相关子查询。像这样:

SELECT 
  g.id, 
  u.name, 
  `u`.`id`                  AS u, 
  g.`created`               AS created, 
  g.`updated`               AS updated,
  COUNT(r.id)               AS reservations, 
  COUNT(t.id)               AS tasks, 
  COUNT(m.id)               AS emails, 
FROM `guests`               AS g
INNER JOIN reservations     AS r  ON r.guest_id = g.id
INNER JOIN tasks            AS t  ON t.guest_id = g.id
INNER JOIN scheduled_emails AS m  ON r.guest_id = g.id
                                 AND r.id       = m.reservation_id 
INNER JOIN
(
   SELECT id, CONCAT(u.`fname`, '', u.`lname`) AS name
   FROM `users`          
)AS u  ON u.id       = g.user_id
GROUP BY g.id, 
         u.id,
         u.name, 
         g.created, 
         g.updated
LIMIT 0, 25;

答案 1 :(得分:1)

不确定为什么你按照自己的方式运行该查询。我建议您使用join表示所有内容,如果不存在left outer join,则会推荐给定表格的结果。

SELECT 
  `guests`.`id`, 
   CONCAT(u.`fname`, '', u.`lname`) "name", 
  `u`.`id` "u", 
   COUNT(r.id) "reservations", 
   COUNT(t.id) "tasks", 
   COUNT(m.id) "emails", 
  `guests`.`created` "created", 
  `guests`.`updated` "updated" 
FROM `guests`
    JOIN `users` AS u ON u.`id` = `guests`.`user_id` 
    JOIN reservations r ON r.guest_id=guests.id
    JOIN tasks t WHERE t.guest_id = guests.id
    JOIN scheduled_emails m ON (r.guest_id = `guests`.`id` AND m.reservation_id = r.id)
GROUP BY g.id, u.id, u.name, g.created, g.updated
LIMIT 0,25