简体   繁体   English

SQL:选择在特定列上唯一的行

[英]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) (ID不是增量的,可以认为是随机的)

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和id2中都唯一的元组,例如,对于上面的示例,所需的输出可能是:

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

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

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