[英]MySQL (multiple) Left Join with sub-query - Unkown Column
I have written a query that should select data from a couple of tables. 我写了一个查询,应该从几个表中选择数据。 However when I added the last LEFT JOIN
with an sub-query the query fails. 但是,当我添加带有子查询的最后一个LEFT JOIN
,查询将失败。 This is because of the following error: 这是由于以下错误:
unkown column 'table1.id' in 'where clause'
So it can't access the columns from the main query, but how do I make it able to access them? 因此它无法访问主查询中的列,但是如何使它能够访问它们呢?
this is the query (although obfuscated because it's sensitive information): 这是查询(尽管因为它是敏感信息而被混淆):
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`
So how to make the subquery's WHERE
clause access the information from the main query? 那么如何使子查询的WHERE
子句访问主查询中的信息呢?
You want an aggregation in the subquery, not a correlation clause: 您希望在子查询中聚合,而不是相关子句:
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
Your code exhibits a bad habit of including columns in the SELECT
that are not in the GROUP BY
. 您的代码表现出一种不良习惯,即在SELECT
中包含GROUP BY
。 This is true in the outer query. 在外部查询中,这是正确的。 In the subquery, I'm not sure if you want a separate row for each series_id
or for each series_id
/ start_time
combination. 在子查询中,我不确定是否要为每个series_id
或每个series_id
/ start_time
组合使用单独的行。 I am guessing the format, which is why there is a MIN()
. 我猜的格式,这就是为什么有一个MIN()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.