如何在 MySQL 的左连接中获取关联行的计数? [英] How do I get a count of associated rows in a left join in MySQL?

查看:28
本文介绍了如何在 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`

这篇关于如何在 MySQL 的左连接中获取关联行的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆