4

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

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 一起使用的结果提供一些帮助吗?

4

1 回答 1

6

只需从您的查询中删除一个字符,它就会完成工作......(将“<>”替换为“<”):

select * from test T1
LEFT OUTER JOIN test T2 on T1.siteid = T2.siteid and T1.id < T2.id
于 2009-08-17T06:20:31.507 回答