![](/img/trans.png)
[英]MySQL: get distinct values from two columns and check whether they occur in two other columns of the same table
[英]Select DISTINCT values from Two Columns using an inner join on the same table in MySQL
我有一個查詢,該查詢從表中選擇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嗎?
也許您可以在子查詢中將LIMIT 20
更改為LIMIT 1
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.