我有这些样本记录:
Master Image Table (named Image)
ImgID aFile AlbumID
1 abc.jpg 1
2 def.jpg 1
3 ghi.jpg 1
1 Qyz.jpg 2
2 Qxz.jpg 2
3 Qxq.jpg 2
1 Xyz.jpg 3
2 Xxz.jpg 3
3 Xxq.jpg 3
Album table
AlbumID Date
1 2013-01-02
2 2014-01-03
3 2012-01-03
每周都会在数据库中添加一个新的图像专辑,并标记日期。我想要一直检索的是仅来自最新专辑的前两个图像文件名。在这种情况下,值应为Qyz.jpg和Qxz.jpg
这是我到目前为止在SQL中尝试的内容:
select aFile from Image,Album where Image.AlbumID=Album.AlbumID and AlbumID in (select AlbumID from Album order by Date Desc limit 0,1) order by ImgID asc limit 0,2
Mysql返回此错误:
This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' []
我相信我正在使用mysql 5.0版。如果没有我升级mysql并且没有我进行两次单独的查询,是否有解决方案?
答案 0 :(得分:1)
这是一种方式。它并没有特别好地扩展,所以如果看起来很慢,那么请看一下使用变量的解决方案。
DROP TABLE IF EXISTS images;
CREATE TABLE images
(image_id INT NOT NULL AUTO_INCREMENT
,filename VARCHAR(12) NOT NULL UNIQUE
,album_id INT NOT NULL
,PRIMARY KEY(album_id,image_id)
)ENGINE = MyISAM;
INSERT INTO images VALUES
(1,'abc.jpg',1),
(2,'def.jpg',1),
(3,'ghi.jpg',1),
(1,'Qyz.jpg',2),
(2,'Qxz.jpg',2),
(3,'Qxq.jpg',2),
(1,'Xyz.jpg',3),
(2,'Xxz.jpg',3),
(3,'Xxq.jpg',3);
DROP TABLE IF EXISTS albums;
CREATE TABLE albums
(album_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,date DATE NOT NULL
);
INSERT INTO albums VALUES
(1,'2013-01-02'),
(2,'2014-01-03'),
(3,'2012-01-03');
SELECT a.*,c.*
FROM albums a
JOIN
( SELECT MAX(date) max_date FROM albums) b
ON b.max_date = a.date
JOIN
( SELECT x.*
FROM images x
JOIN images y
ON y.album_id = x.album_id
AND y.image_id <= x.image_id
GROUP
BY x.album_id
, x.image_id
HAVING COUNT(*) <=2
) c
ON c.album_id = a.album_id;
+----------+------------+----------+----------+----------+
| album_id | date | image_id | filename | album_id |
+----------+------------+----------+----------+----------+
| 2 | 2014-01-03 | 1 | Qyz.jpg | 2 |
| 2 | 2014-01-03 | 2 | Qxz.jpg | 2 |
+----------+------------+----------+----------+----------+
2 rows in set (0.00 sec)
答案 1 :(得分:0)
如果你不介意两个图像都在一个字符串中,那么对于GROUP_CONCAT
和SUBSTRING_INDEX
来说这是一种非常糟糕的方法(因为GROUP_CONCAT
没有{{1} }})。
LIMIT
这应该返回一行,如下所示:
SELECT
SUBSTRING_INDEX(GROUP_CONCAT(aFile ORDER BY ImgID ASC), ',', 2) AS files
FROM Image
JOIN Album USING(AlbumID)
GROUP BY AlbumID
ORDER BY Date DESC
LIMIT 1