简体   繁体   中英

MySQL Query to select 5 records from a join in a sub-query

Kind people of Stackoverflow, I am currently struggling with a small part of my latest project.

Currently working with an image gallery.

For simplicity, I have two tables:

**albums**
album_id, album_title


**media**
media_id, album_id, media_title

I need to display a list of 5 albums and for each album up to 5 items of media in that album.

So I want my query to select 5 albums, and then up to 5 media items that have the same album_id

I want to perform this with the minimum number of queries possible, and also the best performance as possible (so I have this working already by just getting all albums, getting all media and then looping through them, but that isn't scalable if some albums contain hundreds of media items).

I always appreciate the fantastic help I get here. Thank you.

You can get the media in a comma delimited list by using group_concat() :

select a.*,
       substring_index(group_concat(distinct m.media_title), ',', 5)
from albums a join
     media m
     on a.album_id = m.album_id
group by a.album_id
limit 5;

By way of example...

CREATE TABLE colours(colour_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,colour VARCHAR(20) NOT NULL);

INSERT INTO colours VALUES (1,'red'),(2,'orange'),(3,'yellow'),(4,'green'),(5,'blue'),(6,'indigo'),(7,'violet');

CREATE TABLE things
(thing VARCHAR(20) NOT NULL PRIMARY KEY,colour VARCHAR(20));

INSERT INTO things VALUES
('tomato','red'),
('cherry','red'),
('heart','red'),
('ferrari','red'),
('chrysanthemum','orange'),
('orange','orange'),
('banana','yellow'),
('lemon','yellow'),
('sunflower','yellow'),
('caterpillar','green'),
('cucumber','green'),
('grass','green'),
('sky','blue'),
('suede shoes','blue'),
('bluebell','blue'),
('indigo bunting','indigo'),
('violets','violet');


SELECT c.colour
     , y.thing 
  FROM colours c 
  JOIN things x 
    ON x.colour = c.colour 
  JOIN things y 
    ON y.colour = x.colour 
   AND y.thing <= x.thing 
 WHERE c.colour_id <=3 
 GROUP 
    BY c.colour,x.thing 
HAVING COUNT(*) <=3 
 ORDER 
    BY colour_id;
+--------+---------------+
| colour | thing         |
+--------+---------------+
| red    | cherry        |
| red    | cherry        |
| red    | cherry        |
| orange | chrysanthemum |
| orange | chrysanthemum |
| yellow | banana        |
| yellow | banana        |
| yellow | banana        |
+--------+---------------+

http://www.sqlfiddle.com/#!2/36937/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM