SQL在两个不同的列上选择Distinct
我有一张这样的桌子:SQL在两个不同的列上选择Distinct,sql,postgresql,Sql,Postgresql,我有一张这样的桌子: ID from to 1 X Y 2 Y X 3 Z X 4 R L select * from Table1 AS T1 where not exists ( select 1 from Table1 AS T2 where T1.from = T2.to and T1.to = t2.from and T1.id > T2.id )
ID from to
1 X Y
2 Y X
3 Z X
4 R L
select *
from Table1 AS T1
where not exists (
select 1
from Table1 AS T2
where T1.from = T2.to
and T1.to = t2.from
and T1.id > T2.id
)
请注意前两行:
1 X Y
2 Y X
我想要的是防止反转列/不同列上的值相同,或从!=到,我希望SQL返回:
ID from to
1 X Y
3 Z X
4 R L
SQL能做到这一点吗?我将这些列组合在一起并进行排序。 然后,我使用GROUPBY删除重复项。Se演示在这里:
我将这些列组合在一起并将它们排序。 然后,我使用GROUPBY删除重复项。Se演示在这里: DISTINCT子句不是此作业的合适工具,但您可以像这样轻松地消除重复行:
ID from to
1 X Y
2 Y X
3 Z X
4 R L
select *
from Table1 AS T1
where not exists (
select 1
from Table1 AS T2
where T1.from = T2.to
and T1.to = t2.from
and T1.id > T2.id
)
下面是一个工作示例:DISTINCT子句不是此作业的正确工具,但您可以像这样轻松地消除重复行:
ID from to
1 X Y
2 Y X
3 Z X
4 R L
select *
from Table1 AS T1
where not exists (
select 1
from Table1 AS T2
where T1.from = T2.to
and T1.to = t2.from
and T1.id > T2.id
)
下面是一个工作示例:您还可以使用最小值和最大值函数从两列中查找最小值和最大值
select * from table t
where id in (
select min(id) from table
group by least(from, to), greatest(from, to)
)
您还可以使用最小值和最大值函数从两列中查找最小值和最大值
select * from table t
where id in (
select min(id) from table
group by least(from, to), greatest(from, to)
)
您可以通过从和到的标准化组合进行分组:
联机示例:您可以按from和to的标准化组合进行分组:
在线示例:您使用的是MySQL还是PostgreSQL?@David PostgreSQLwant是防止反转值的出现,您是希望将其作为一个约束防止输入,还是仅在select语句中抑制反转值的输出,不清楚您真正想要的是什么。您使用的是MySQL还是PostgreSQL?@David PostgreSQLwant是为了防止反转值,您是否希望将其作为一个约束来阻止,以便无法输入它,还是仅在select语句中抑制反转值的输出,不清楚您真正想要的是什么。