如何在 MySQL 的左连接中获取关联行的计数?

2022-01-23 00:00:00 join sql select subquery mysql

我有两个表,一个 vehicle 表,其中包含列:

I have two tables, a vehicle table with columns:

  • id
  • 股票
  • 年份
  • 制作
  • 模型

和一个带有列的 images 表:

and an images table with columns:

  • id
  • vehicle_id
  • 名称
  • 标题
  • 默认 tinyint(1)

我正在尝试列出车辆的信息、默认图像以及车辆拥有的图像总数.目前我正在使用以下 SELECT 语句:

I am trying to list the vehicle's information, its default image, and a total count of images the vehicle has. Currently I am using the following SELECT statement:

SELECT vehicle.id, vehicle.stock, vehicle.year,
    vehicle.make, vehicle.model, images.name,
    COUNT(images.id)
FROM vehicle
LEFT JOIN images
ON vehicle.id = images.vehicle_id

我最初使用的是:

ON vehicle.id = images.vehicle_id AND images.default = 1

但是根据数据库中是否存在默认图像,图像计数将仅为 1 或 0.我曾尝试使用 UNION 和其他 SELECT 语句,但我仍然无法获得正确的结果.我需要使用两个 SELECT 语句还是有其他方法可以使用 JOINUNION 来处理它?<​​/p>

but then the images count would only be 1 or 0 depending if there was a default image in the database. I have tried using UNION and other SELECT statements but I am still unable to get a proper result. Do I need to use two SELECT statements or is there another way to handle it with JOIN or UNION?

推荐答案

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`

相关文章