表格:
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
但是这种返回结果当然不好;) 寻求帮助:)
答案 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
答案 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);