2016-02-19 61 views
1

我有這些樣本記錄:在mysql子查詢中使用限制。最簡單的選擇?

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

如果你不介意的兩種圖像在一個單一的字符爲,那麼這裏有GROUP_CONCATSUBSTRING_INDEX一個真正哈克的方式(因爲GROUP_CONCAT沒有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 

這應返回一行,像這樣:

files 
Qyz.jpg,Qxz.jpg 
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)