简体   繁体   中英

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. 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?

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 . 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. I am guessing the format, which is why there is a MIN() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM