[英]MySQL (multiple) Left Join with sub-query - Unkown Column
我寫了一個查詢,應該從幾個表中選擇數據。 但是,當我添加帶有子查詢的最后一個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
子句訪問主查詢中的信息呢?
您希望在子查詢中聚合,而不是相關子句:
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()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.