How do I get a count of associated rows in a left join in MySQL?(如何在 MySQL 的左连接中获取关联行的计数?)
问题描述
我有两个表,一个 vehicle 表,其中包含列:
I have two tables, a vehicle table with columns:
id股票年份制作模型
和一个带有列的 images 表:
and an images table with columns:
idvehicle_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 语句还是有其他方法可以使用 JOIN 或 UNION 来处理它?</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 的左连接中获取关联行的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 MySQL 的左连接中获取关联行的计数?
基础教程推荐
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在多列上分布任意行 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
