MySQL Query从子查询中的连接中选择5条记录

时间:2013-06-03 13:58:12

标签: php mysql join subquery

Stackoverflow的善良人士,我目前正在努力处理我最新项目的一小部分。

目前正在使用图片库。

为简单起见,我有两个表:

**albums**
album_id, album_title


**media**
media_id, album_id, media_title

我需要显示5张专辑的列表,并为每张专辑显示该专辑中最多5项媒体。

所以我希望我的查询选择5个专辑,然后最多5个具有相同album_id的媒体项目

我想用尽可能少的查询来执行此操作,并且尽可能提供最佳性能(因此我已经通过获取所有专辑,获取所有媒体然后循环遍历它们来实现此功能,但这不是如果某些专辑包含数百个媒体项目,则可以扩展。)

我总是很感激我来到这里的绝佳帮助。谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用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;

答案 1 :(得分:1)

举例来说......

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