舉例來說...
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
哦,好的。我沒有想過這樣做。我故意簡化了我的OP表結構。媒體表格連接到其他表格,並有更多字段,因此最終將媒體記錄作爲PHP中的關聯數組而非逗號分隔會更有用。但是,這是一個很好的解決方案。 – SpongeBobPHPPants