简体   繁体   English

在MySQL的同一张表上使用内部联接从两列中选择DISTINCT值

[英]Select DISTINCT values from Two Columns using an inner join on the same table in MySQL

I have a query that selects 20 rows from a table, loops, and pulls a single row from the same table that falls in the desired score range. 我有一个查询,该查询从表中选择20行,循环并从同一表中拉出属于所需分数范围的单行。 The found row is then deleted so that it will not be selected again. 然后将删除找到的行,以便不再选择它。

user_id is unique and some rows have col1=0 and others have col1=1, therefore the second query will never select a row from the first query. user_id是唯一的,有些行的col1 = 0,有些行的col1 = 1,因此第二个查询永远不会从第一个查询中选择一行。

The temp table looks like this: 临时表如下所示:

user_id  col1
-------------------
1        0
2        0
3        1
4        1

The user table looks like this: 用户表如下所示:

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");
}

This works just fine, however I was trying to turn this into a single query, but I keep getting duplicate values, and I can't seem to weed them out. 这样做很好,但是我试图将其转换为单个查询,但是我一直在获取重复的值,而且似乎无法清除它们。

 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

I get 20 rows with temp.user_id being unique, but duplicates with t1.user_id. 我得到20行,其中temp.user_id是唯一的,但与t1.user_id重复。

For example: 例如:

temp.user_id    t1.user_id
----------------------------
1               6
2               7
3               7 
4               7
5               8

and I want: 而且我要:

temp.user_id      t1.user_id
-----------------------------
1                 6
2                 7
3                 8 
4                 9
5                 10

Any idea how to make it so that no user_id is repeated in either column? 知道如何做到这一点,以便在任一列中都不会重复user_id吗?

也许您可以在子查询中将LIMIT 20更改为LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM