MySQL(多个)左连接子查询 - 未知列

时间:2016-12-08 17:34:14

标签: mysql sql subquery left-join

我编写了一个应该从几个表中选择数据的查询。但是,当我使用子查询添加最后一个LEFT JOIN时,查询失败。这是因为以下错误:

unkown column 'table1.id' in 'where clause'

因此,它无法访问主查询中的列,但如何才能访问它们?

这是查询(虽然因为它的敏感信息而被混淆):

SELECT `table1`.*, `table2`.`max_people`, COUNT(`table3`.`id`) as c_p, dates.date 
FROM `table1` 
LEFT JOIN `table2` 
ON `table1`.`c_id`=`table2`.`id` 
LEFT JOIN `table3` 
ON `table1`.`id`=`table3`.`series_id` 
LEFT JOIN (SELECT `table4`.`series_id`,MIN(`table4`.`date`) as date, `table4`.`start_time` FROM `table4` WHERE `table4`.`series_id`=`table1`.`id`) dates 
ON `table1`.`id`=dates.series_id 
GROUP BY `table1`.`id` 
ORDER BY `table1`.`c_id`, `table1`.`name`

那么如何让子查询的WHERE子句访问主查询中的信息?

1 个答案:

答案 0 :(得分:0)

您希望在子查询中进行聚合,而不是相关子句:

FROM `table1` t1 LEFT JOIN
     `table2` t2
     ON t1.`c_id` = t2.`id` LEFT JOIN
     `table3` t3
     ON t1.`id` = t3.`series_id` LEFT JOIN
     (SELECT t4.`series_id`, MIN(t4.`date`) as date, 
             MIN(t4.`start_time`) as start_time  -- this is a guess
      FROM `table4` t4
      GROUP BY t4.`series_id`
     ) dates 
     ON t1.`id` = dates.series_id 

您的代码养成了在SELECT中包含不在GROUP BY中的列的坏习惯。在外部查询中也是如此。在子查询中,我不确定您是否要为每个series_id或每个series_id / start_time组合分别添加一行。我猜这种格式,这就是MIN()

的原因