我有一个包含记录的表,它有一个名为gallery的表。我插入了太多照片,我想从每个图库中只选择2张随机照片。
这里是我的结构化
CREATE TABLE IF NOT EXISTS `gallery` (
`gallery_id` int(11) NOT NULL,
`gallery_name` varchar(100) NOT NULL,
`gallery_name_seo` varchar(120) NOT NULL,
`gallery_client` varchar(100) NOT NULL,
`gallery_date` date NOT NULL,
`gallery_type` int(2) NOT NULL,
`gallery_desc` text,
`gallery_publish` char(1) NOT NULL DEFAULT 'N' COMMENT 'Y = Yes & N = No',
`gallery_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`deleted` int(11) NOT NULL DEFAULT '0'
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
这里是另一张表
CREATE TABLE IF NOT EXISTS `gallery_photo` (
`id` int(10) NOT NULL,
`id_gallery` int(10) NOT NULL,
`file_name` varchar(255) NOT NULL,
`file_added` date NOT NULL,
`deleted` smallint(6) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=latin1;
这里有许多例子,但我很难理解,
如何根据我的问题创建查询。?
谢谢
答案 0 :(得分:0)
以下查询会为每个id_gallery
提供1张随机照片:
SELECT *
FROM (SELECT * FROM `gallery_photo` ORDER BY RAND()) as `rand_photos`
GROUP BY rand_photos.id_gallery
你可以自己UNION
为每个画廊获取2张随机照片:
SELECT *
FROM (SELECT * FROM `gallery_photo` ORDER BY RAND()) as `rand_photo1`
GROUP BY rand_photo1.id_gallery
UNION
SELECT *
FROM (SELECT * FROM `gallery_photo` ORDER BY RAND()) as `rand_photo2`
GROUP BY rand_photo2.id_gallery
ORDER BY id_gallery