How do I get a count of associated rows in a left join in MySQL?

前端 未结 3 1284
梦谈多话
梦谈多话 2021-02-07 06:08

I have two tables, a vehicle table with columns:

  • id
  • stock
  • year
  • make
3条回答
  •  醉酒成梦
    2021-02-07 06:47

    SELECT 
        `vehicle`.`id`, 
        `vehicle`.`stock`, 
        `vehicle`.`year`, 
        `vehicle`.`make`, 
        `vehicle`.`model`, 
        `images`.`name`,
        (
            SELECT COUNT(*) 
            FROM `images` 
            WHERE `vehicle_id` = `vehicle`.`id`
        ) AS `image_count`
    FROM `vehicle`
    LEFT JOIN `images`
    ON `images`.`vehicle_id` = `vehicle`.`id`
    WHERE `images`.`default`
    

提交回复
热议问题