随机获取表若干行
发布时间:2020-12-11 23:13:39 所属栏目:MySql教程 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 CREATE DEFINER=`root`@`%` PROCEDURE `rand_data`(IN `tbName` VARCHAR(50),IN `rowCnt` INT,IN `tbKey` VARCHAR(50))LANGUAGE SQLNOT DETERMINISTIC
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 CREATE DEFINER=`root`@`%` PROCEDURE `rand_data`(IN `tbName` VARCHAR(50),IN `rowCnt` INT,IN `tbKey` VARCHAR(50)) LANGUAGE SQL NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER COMMENT '随机获取若干记录,只适用于单主键表' BEGIN #获取主键名 IF tbKey IS NOT NULL THEN SET @tbKey=tbKey;#参数里面已经有,这种情况比较快 ELSE #参数里面没,从系统表查找主键,比较耗时 SELECT @tbKey:=c.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS t,INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS c WHERE t.TABLE_NAME = c.TABLE_NAME AND t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_SCHEMA = database() AND t.TABLE_NAME = tbName AND t.CONSTRAINT_TYPE = 'PRIMARY KEY'; END IF; #获取最大id,最小id和记录数 SET @getMaxIdSql = CONCAT('SELECT @maxId:=MAX(',@tbKey,'),','@minId:=MIN(','@totalCnt:=COUNT(',')',' FROM `',tbName,'`;'); PREPARE getMaxId FROM @getMaxIdSql; EXECUTE getMaxId; DEALLOCATE PREPARE getMaxId; #创建临时表 DROP TABLE IF EXISTS rand_tt; SET @temTbSql = CONCAT('CREATE TEMPORARY TABLE rand_tt SELECT 0 aid,tb.* FROM `','` tb LIMIT 0;'); PREPARE temTb FROM @temTbSql; EXECUTE temTb; DEALLOCATE PREPARE temTb; #构建获取一条记录的sql SET @randRowSql = CONCAT('INSERT INTO rand_tt SELECT @cnt:[email?protected]+1 aid,tb.* FROM ',' tb WHERE tb.','=?;'); PREPARE addRow FROM @randRowSql; #生成随机记录 SET @cnt=0; insertLoop: LOOP SET @id=FLOOR(RAND()*(@[email?protected])[email?protected]); IF NOT EXISTS (SELECT id FROM rand_tt WHERE [email?protected]) THEN EXECUTE addRow USING @id; IF @cnt >= rowCnt OR @cnt >= @totalCnt THEN LEAVE insertLoop; END IF; END IF; END LOOP insertLoop; DEALLOCATE PREPARE addRow; #返回数据 ALTER TABLE rand_tt DROP COLUMN aid; SELECT * FROM rand_tt; END 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |