欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

mysql随机获取优化语句

程序员文章站 2022-06-08 13:44:59
...
在网上找了一个随机取数语句,结合了自己的需求,运行出错,
看了半天没发现出错的地方,求指点
$str="select * from dizhi where shijiancuo>'$times' GROUP BY user HAVING COUNT(user) > 4 AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM dizhi)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id ASC LIMIT 1" ;

回复讨论(解决方案)

错误信息是什么?

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in D:\www\AppServ\www\tuijianshuchu.php on line 23

23代码如下
$result=mysql_query($str, $con);  //送出查?	$rows=mysql_num_rows($result); //23行

因为是你的sql语句出错了 你把$str语句打印下看是什么东东

$str在1楼贴了

$result=mysql_query($str, $con) or die(mysql_error());

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM dizhi)) AS id) AS t2 ' at line 1

select * from
(select * from dizhi where shijiancuo>'$times' GROUP BY user HAVING COUNT(user) > 4) AS t1
JOIN
(SELECT ROUND(RAND() * (SELECT MAX(id) FROM dizhi)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id ASC LIMIT 1

JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM dizhi)) AS id from dizhi) AS t2

8楼的不行,7楼的OK,多谢了
一直没搞明白这句的意思

 (SELECT ROUND(RAND() * (SELECT MAX(id) FROM dizhi)) AS id) AS t2 

网上说ROUND 函数用于把数值字段舍入为指定的小数位数,所以不太理解这语句的结果是什么

RAND 产生一个小于 1 的随机数
SELECT MAX(id) FROM dizhi 取得表 dizhi 中最大的 id 值
ROUND 四舍五入化为整数

这个查询指令的意思是:
任取表中的一个 id 值

理解了,3Q。