0

クエリの最適化に取り組んでいます

(1つのテーブルから2人のランダムなユーザーを選択します)

id  | name |  total | img
------------------------ --
1    user1   500      1
2    user2   600      2
3    user3   650      3

結果とABS(合計1-合計2)<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への接続は大丈夫です(別のクエリが機能しています)

4

3 に答える 3

1

2つのランダムなレコードを選択するために、私は通常、

// Whatever your query is
order by rand() 
limit 2

次に、これら2つのランダムレコードから必要な計算を実行できます。

于 2013-03-09T11:24:02.647 に答える
1

これがあなたの解決策です:

SELECT u1.id1, u2.id2, u1.name1, u2.name2, u1.total1, u2.total2, u1.img1, u2.img2 
FROM 
(
    SELECT u.id id1, u.name name1, u.total total1, u.img img1 
    FROM users u 
    ORDER BY RAND()
) u1
CROSS JOIN
(
    SELECT u.id id2, u.name name2, u.total total2, u.img img2 
    FROM users u 
    ORDER BY RAND()
) u2
WHERE u1.id1 != u2.id2 AND ABS(u1.total1 - u2.total2) < 200
LIMIT 0,1;

デモ

于 2013-03-09T11:42:57.970 に答える
0

で試してみてprepare()くださいexecute()

$stmt = $dbh->prepare(
  "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");
$stmt->execute(array($target));

$rs = $stmt->fetchAll();

2つではなく1つのクエリはどうですか:rand()計算を減らして

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(select *, rand() randval from users) C1, users C2
  WHERE C1.id <> C2.id AND ABS(C1.total - C2.total) < 200
  ORDER BY C1.randval DESC
  LIMIT 1;
于 2013-03-09T11:21:17.810 に答える