如果第三列具有相同的值,如何从两列中选择唯一值

时间:2019-04-28 12:18:32

标签: sql mariadb

表格:

id second_id status
1  2         1
2  1         0
1  3         1
3  1         1
1  4         1
4  1         1

我尝试仅选择该对中具有相同状态的唯一值 输出:

id second_id status
1  3         1
1  4         1

我尝试

SELECT table.id, table.second_id, table.status FROM table 
WHERE table.id = 1 and table.status = 1 

但是这种返回结果当然不好;) 寻求帮助:)

2 个答案:

答案 0 :(得分:2)

执行此操作的一种方法是将表JOIN自身放置,以寻找具有相同id的{​​{1}}和second_id值。我们还检查第二个表的status值是否大于第一个表,以避免重复:

id

输出:

SELECT t1.*
FROM test t1
JOIN test t2 ON t2.id = t1.second_id
            AND t2.second_id = t1.id
            AND t2.status = t1.status
            AND t2.id > t1.id

Demo on dbfiddle

答案 1 :(得分:0)

一种方法使用exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.second_id = t.id and
                    t2.id = t.second_id and
                    t2.status = t.status
             );

或者,使用in和元组表示起来更简单:

select t.*
from t
where (id, second_id, status) in
          (select second_id, id, status from t);