我有一个查询,它从表中选择 20 行,循环并从同一个表中拉出位于所需分数范围内的单行。然后删除找到的行,这样就不会再次选择它。
user_id 是唯一的,有些行 col1=0,有些行 col1=1,因此第二个查询永远不会从第一个查询中选择一行。
临时表如下所示:
user_id col1
-------------------
1 0
2 0
3 1
4 1
用户表如下所示:
user_id score
-----------------
1 1000
2 2000
3 3000
4 4000
$res = do_query("SELECT temp.user_id,user.score
FROM temp,user
WHERE temp.col1=0 AND temp.user_id=user.user_id LIMIT 20");
while (($row = mysql_fetch_row($res))) {
$score = $row[1];
$alt_res = do_query("SELECT temp.user_id, user.score
FROM temp,user
WHERE temp.col1=1 AND temp.user_id=user.user_id
AND user.score<$score AND user.score>$score*0.66 LIMIT 1");
$alt_row = mysql_fetch_row($alt_res)
$user_id = $alt_row[0];
do_query("DELETE FROM temp WHERE user_id=$user_id");
}
这工作得很好,但是我试图把它变成一个单一的查询,但我不断得到重复的值,我似乎无法清除它们。
SELECT temp.user_id,t1.user_id,t1.score FROM (
SELECT temp.user_id,user.score
FROM temp,user
WHERE temp.col1=0 AND temp.user_id=user.user_id LIMIT 20) AS t1,temp,user
WHERE temp.col1=1 AND temp.user_id=user.user_id
AND t1.score<user.score AND t1.score>user.score*0.66 GROUP BY temp.user_id
我得到 20 行,其中 temp.user_id 是唯一的,但与 t1.user_id 重复。
例如:
temp.user_id t1.user_id
----------------------------
1 6
2 7
3 7
4 7
5 8
而且我要:
temp.user_id t1.user_id
-----------------------------
1 6
2 7
3 8
4 9
5 10
知道如何做到这一点,以便在任一列中都没有重复 user_id 吗?