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

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

I have two tables, a vehicle table with columns:

  • id
  • stock
  • year
  • make
相关标签:
3条回答
  • 2021-02-07 06:36

    In the way the anser suggests, you get repeated values of "vehicle". A better way, is to group results. Try without the JOIN :

    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`
    
    WHERE `images`.`default`
    
    0 讨论(0)
  • 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`
    
    0 讨论(0)
  • 2021-02-07 07:00

    Let me make it clear for everyone!

    Task: Print 3 columns table:

    1. Vehicles (titles) from vehicles table.
    2. Amount of comments for each vehicle from comments table.
    3. Amount of images for each vehicle from images table.

    Expected output (just an example):

    +----------------------+----------------+--------------+
    |        title         | comments_count | images_count |
    +----------------------+----------------+--------------+
    | BMW X6               |             35 |            9 |
    | Audi A6              |              3 |            5 |
    | Volkswagen Passat B6 |             78 |            6 |
    | Volkswagen Passat B5 |            129 |            4 |
    +----------------------+----------------+--------------+
    

    Solution:

    SELECT 
        vehicles.title,
        (SELECT COUNT(*) FROM comments WHERE vehicles.id = comments.vehicle_id) AS comments_count,
        (SELECT COUNT(*) FROM images WHERE vehicles.id = images.vehicle_id) AS images_count
    FROM vehicles
    
    0 讨论(0)
提交回复
热议问题