I use Yii framework to develop a website, I want to know how to get the last 5 images orderd by create_time but not within the same album by using Yii active record and by plain SQL.
here’s my albums table:
CREATE TABLE IF NOT EXISTS `tbl_album` (
`album_id` int(11) NOT NULL AUTO_INCREMENT,
`album_name` varchar(45) DEFAULT NULL,
`album_folder_name` int(11) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`create_user_id` int(11) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`update_user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`album_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=55 ;
and here’s my images table:
CREATE TABLE IF NOT EXISTS `tbl_image` (
`image_id` int(11) NOT NULL AUTO_INCREMENT,
`image_name` varchar(100) DEFAULT NULL,
`image_description` varchar(100) DEFAULT NULL,
`image_album_id` int(11) NOT NULL,
`create_time` datetime DEFAULT NULL,
`create_user_id` int(11) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`update_user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`image_id`),
KEY `fk_image_album` (`image_album_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
please note that I use “create_time” for sorting images.
Again, I need a query to get the last 5 images orderd by create_time but not within the same album by Yii active record and plain SQL.
for example the last 7 images are:
a.jpg in the album 7
b.jpg in the album 5
c.jpg in the album 7
d.jpg in the album 6
e.jpg in the album 3
f.jpg in the album 4
g.jpg in the album 2
h.jpg in the album 1
I need the query result to be like the following:
a.jpg in album 7
b.jpg in album 5
d.jpg in album 6
e.jpg in album 3
f.jpg in album 4
not like the following:
a.jpg in album 7
b.jpg in album 5
c.jpg in album 7
d.jpg in album 6
e.jpg in album 3
Thanks in advance.
Try this:
The
JOINwith:will insure that for each album, the first image will be returned. Therefore you will got only one image for each album, then
LIMIT 5will limit the result set to be only 5 albums.SQL Fiddle Demo
Note that: The
ORDER BYclause will determine which five albums will be returned by theLIMIT 5clause. So don’t expect that the albums are returned in the way they are stored as the expected result in your question, because records in the table has no specific order. They are stored as a set, and you have to specify anORDER BYclause in your query to get them in a specific order.Update: IF you are looking for the last created image for each album, use the
MAX(creaet_time)instead like so:Updated SQL Fiddle Demo
Update 2: For the duplicate values, use the
DISTINCTkeyword, or you can use theMAX(image_id)instead, since theimage_idis autoincremental, like so:Updated SQL Fiddle Demo