Ehsan Mehralian
Ehsan Mehralian

Reputation: 345

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.

Upvotes: 0

Views: 48

Answers (2)

Ferdinand Gaspar
Ferdinand Gaspar

Reputation: 2063

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

Upvotes: 0

Barmar
Barmar

Reputation: 780688

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.

Upvotes: 1

Related Questions