如何在与自身连接表时排除重复的行

时间:2009-08-17 06:06:02

标签: sql oracle group-by outer-join

这是一个示例表来帮助说明我的问题:

mysql> select * from test;
+----+--------------+--------+
| id | type         | siteid |
+----+--------------+--------+
|  1 | First Visit  |    100 |
|  2 | Second Visit |    100 |
|  3 | First Visit  |    300 |
|  4 | First Visit  |    400 |
|  5 | Second Visit |    500 |
|  6 | Second Visit |    600 |
+----+--------------+--------+

我正在尝试将表连接到自身,将具有相同siteid值的行组合在一起。这是我的尝试:

mysql> select * from test T1
    -> LEFT OUTER JOIN test T2 on T1.siteid = T2.siteid and T1.id <> T2.id;
+----+--------------+--------+------+--------------+--------+
| id | type         | siteid | id   | type         | siteid |
+----+--------------+--------+------+--------------+--------+
|  1 | First Visit  |    100 |    2 | Second Visit |    100 |
|  2 | Second Visit |    100 |    1 | First Visit  |    100 |
|  3 | First Visit  |    300 | NULL | NULL         |   NULL |
|  4 | First Visit  |    400 | NULL | NULL         |   NULL |
|  5 | Second Visit |    500 | NULL | NULL         |   NULL |
|  6 | Second Visit |    600 | NULL | NULL         |   NULL |
+----+--------------+--------+------+--------------+--------+

这基本上是我正在寻找的结果,除了前2行。我想消除其中一个。所以,我尝试了以下内容:

mysql> select * from test T1
    -> LEFT OUTER JOIN test T2 on T1.siteid = T2.siteid and T1.id <> T2.id
    -> GROUP BY T1.siteid;
+----+--------------+--------+------+--------------+--------+
| id | type         | siteid | id   | type         | siteid |
+----+--------------+--------+------+--------------+--------+
|  1 | First Visit  |    100 |    2 | Second Visit |    100 |
|  3 | First Visit  |    300 | NULL | NULL         |   NULL |
|  4 | First Visit  |    400 | NULL | NULL         |   NULL |
|  5 | Second Visit |    500 | NULL | NULL         |   NULL |
|  6 | Second Visit |    600 | NULL | NULL         |   NULL |
+----+--------------+--------+------+--------------+--------+

这正是我正在寻找的输出。但是,我开始了解这不是使用GROUP BY的标准方法,上面的语句在ORACLE上失败,给了我一个

常规SQL错误。
ORA-00979:不是GROUP BY表达式

任何人都可以提供一些关于如何获得结果的帮助,例如最后一个表并且与ORACLE一起使用吗?

1 个答案:

答案 0 :(得分:6)

只需从查询中删除一个字符即可完成工作...(将“&lt;&gt;”替换为“&lt;”):

select * from test T1
LEFT OUTER JOIN test T2 on T1.siteid = T2.siteid and T1.id < T2.id