[英]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. 作为Stackoverflow的好朋友,我目前正在为我的最新项目中的一小部分苦苦挣扎。
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. 我需要显示5张专辑的列表,并且每张专辑最多显示该专辑中的5种媒体。
So I want my query to select 5 albums, and then up to 5 media items that have the same album_id 因此,我希望查询选择5个专辑,然后最多选择5个具有相同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()
: 您可以使用
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 http://www.sqlfiddle.com/#!2/36937/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.