简体   繁体   中英

SQL: select rows which are unique on specific columns

I have a table of questions pairs with the scheme of

id1     question1    id2    question2
1123    q1           2      q2
1123    q1           3      q3
1123    q1           1231   q142
2431    q12          1231   q142

( ids are not incremental and can be considered random)

I want to select tuples which are unique in both of id1 and id2, for example for the above example a desired output might be:

id1     question1    id2    question2
1123    q1           2      q2
2431    q12          1231   q142

thank you in advance.

Use nested queries.

SELECT *
FROM (SELECT *
      FROM yourTable
      GROUP BY id1) AS x
GROUP BY id2

However, it's unpredictable how this will do the grouping. If the subquery chooses

id1     id2
1123    1231
2431    1231

then the final result will be:

id1     id2
1123    1231

or

id1     id2
2431    1231

I'm not sure how to change it so it produces the result with the most possible combinations.

you can use ranking as well

SELECT id1,
       question1,
       id2,
       question2
  FROM (SELECT CASE id1 
                    WHEN @curType 
                    THEN @curRow := @curRow + 1 
                    ELSE @curRow := 1 AND @curType := id1 
                END rank,
                id1,
                question1,
                id2,
                question2
           FROM q,
                (SELECT @curRow := 0, @curType := '') r
          ORDER BY  id1, id2
        ) t
 WHERE rank = 1

Result

rank id1  id2
1    1123 2
1    2431 1231

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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