我正在优化查询
(从 1 个表中随机选择 2 个用户)
id | name | total | img
------------------------ --
1 user1 500 1
2 user2 600 2
3 user3 650 3
需要结果和 ABS(total1 -total2) < 200
id1 | id2| name1 | name2 | img1 | img2 | total1 | total2
------------------------ -------------------------------------
1 3 user1 user3 1 3 500 650
为了获得更多性能重写这个:
SELECT
C1.id AS id1, C1.img AS img1, C1.name AS name1,
C2.id AS id2, C2.img AS img2, C2.name AS name2,
C1.total AS total1, C2.total AS total2
FROM users C1, users C2
WHERE C1.id <> C2.id
AND ABS(C1.total - C2.total) < 200
ORDER BY RAND()
LIMIT 1
至
$dbh = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw");
$rs = $dbh->query(
"SELECT COUNT(*) AS 'count'
FROM users C1, users C2
WHERE C1.id <> C2.id
AND ABS(C1.total - C2.total) < 200");
$target = rand(0,$rs[0]['count']);
$rs = $dbh->query(
"SELECT
C1.id AS id1, C1.img AS img1, C1.name AS name1,
C2.id AS id2, C2.img AS img2, C2.name AS name2,
C1.total AS total1, C2.total AS total2
FROM users C1, users C2
WHERE C1.id <> C2.id
AND ABS(C1.total - C2.total) < 200
LIMIT ?,1",
array($target));
foreach ($rs as $row)
{
print $row['name1'];
}
返回 empry 结果,我错过了什么,与 db 的连接正常(另一个查询正在工作)