表结构如下:
CREATE TABLE `data` ( `dataId` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT ""数据编号"", `dataName` VARCHAR(30) NOT NULL COMMENT ""数据名称"", `pubState` INT(1) NOT NULL DEFAULT ""0"" COMMENT ""发布状态:0:未审核,1:审核已通过,2:审核未通过"", `recommend` INT(1) NOT NULL DEFAULT ""0"" COMMENT ""0:显示,1:推荐,2:隐藏"", `isDeleted` INT(1) NOT NULL DEFAULT ""0"" COMMENT ""删除标记,0未删除1已删除"", PRIMARY KEY (`dataId`) ) COLLATE=""utf8_general_ci"" ENGINE=InnoDB AUTO_INCREMENT=193443 ;
CREATE TABLE `topic` ( `topicId` BIGINT(20) NOT NULL AUTO_INCREMENT, `topicName` VARCHAR(100) NULL DEFAULT NULL COMMENT ""主题名称"", `iconClass` VARCHAR(20) NULL DEFAULT NULL COMMENT ""图标样式"", PRIMARY KEY (`topicId`) ) COMMENT=""主题表"" COLLATE=""utf8_general_ci"" ENGINE=InnoDB AUTO_INCREMENT=21 ;
CREATE TABLE `userTopic` ( `userTopicId` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT ""表主键"", `userId` BIGINT(20) NOT NULL COMMENT ""用户id,与users表主键相同"", `topicId` BIGINT(20) NOT NULL COMMENT ""主题id,与topic表主键相同"", PRIMARY KEY (`userTopicId`) ) COMMENT=""记录每个用户感兴趣的主题"" COLLATE=""utf8_general_ci"" ENGINE=InnoDB AUTO_INCREMENT=98 ;
CREATE TABLE `datatopic` ( `datatopicId` BIGINT(20) NOT NULL AUTO_INCREMENT, `dataId` BIGINT(20) NULL DEFAULT NULL, `topicId` BIGINT(20) NULL DEFAULT NULL, PRIMARY KEY (`datatopicId`), INDEX `dataId_topicId` (`dataId`, `topicId`) ) COLLATE=""utf8_general_ci"" ENGINE=InnoDB AUTO_INCREMENT=532552 ;
本人希望能实现下面的SQL语句的效果,但是用ORDER BY RAND()太慢,问一下该怎么办?
SELECT d.dataId, d.dataName, d.orgName, t.iconClass FROM userTopic u, topic t, data d, datatopic dt WHERE u.topicId=t.topicId AND d.pubState=1 AND d.dataId=dt.dataId AND u.topicId=dt.topicId AND d.isDeleted!=1 AND d.recommend!=2 AND u.userId=#{userId} ORDER BY RAND() LIMIT 6
解决方案:40分
假如随便取,并且某张表中ID连续或近似连续,则可以先生成 1-max(id)之间的五个随机数,然后通过这五个随机数去取记录。