Selecting the count of rows on second table based on foreign key in MySQL

StackOverflow https://stackoverflow.com/questions/22182542

  •  05-06-2023
  •  | 
  •  

Вопрос

So I have this table of albums and images. Images have a column named album_id which takes the album ID they are sitting on. So far so good.

Now I'm in need to select information from the Albums table and I also need the count of images for each album row. I tried using a LEFT JOIN and a COUNT(*), but it would return only one row, which is highly inefficient for my case.

This is the original query I'm using which wont return anything count related:

SELECT album_id, album_name, album_preview, album_owner, album_time, album_access 
FROM imgzer_albums WHERE album_owner = SOME_VALUE

And this is the query with the LEFT JOIN:

SELECT a.album_id, a.album_name, a.album_preview, a.album_owner, a.album_time, a.album_access, COUNT(i.*) AS images 
FROM imgzer_albums a 
LEFT JOIN imgzer_images i 
    ON a.album_id = i.album_id 
WHERE album_owner = SOME_VALUE

How do I get the images count for each corresponding album ID without being limited to one result only?

Это было полезно?

Решение

Try This

SELECT a.album_id, a.album_name, a.album_preview, a.album_owner, a.album_time, a.album_access, COUNT(i.*) AS images 
FROM imgzer_albums a 
LEFT JOIN imgzer_images i 
    ON a.album_id = i.album_id 
WHERE album_owner = SOME_VALUE
GROUP BY a.album_id

Другие советы

a solution without grouping is a correlated query:

SELECT a.album_id, a.album_name, a.album_preview, a.album_owner, a.album_time, a.album_access, 
(select COUNT(*) from imgzer_images i where a.album_id = i.album_id) AS images 
FROM imgzer_albums a 
WHERE album_owner = SOME_VALUE
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top