Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL在两个不同的列上选择Distinct_Sql_Postgresql - Fatal编程技术网

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语句中抑制反转值的输出,不清楚您真正想要的是什么。