【发布时间】:2018-12-04 19:36:02
【问题描述】:
以下是创建表的代码
create table residences(
id integer
references students,
building text
references buildings(name),
room text
);
以下是查询代码。
select a.id, b.id, a.building, a.room
from residences as a, residences as b
where a.building = b.building
and a.room = b.room
and a.id > b.id
order by a.building, a.room;
| id | id | building | room |
+--------+--------+----------+------+
| 881256 | 413001 | Crosby | 10 |
| 741532 | 496747 | Crosby | 19 |
| 931027 | 612413 | Crosby | 31 |
| 958827 | 170267 | Dolliver | 1 |
| 707536 | 104131 | Dolliver | 14 |
| 505241 | 477801 | Dolliver | 8 |
| 824292 | 118199 | Kendrick | 1A |
| 231742 | 105540 | Kendrick | 3B |
+--------+--------+----------+------+
我都试过了
and a.id > b.id
和
and a.id < b.id
两者都产生了相同的结果。
但是,当我使用时
and a.id != b.id
它没有工作,而是产生了
+--------+--------+----------+------+
| id | id | building | room |
+========+========+==========+======+
| 413001 | 881256 | Crosby | 10 |
| 881256 | 413001 | Crosby | 10 |
| 496747 | 741532 | Crosby | 19 |
| 741532 | 496747 | Crosby | 19 |
| 612413 | 931027 | Crosby | 31 |
| 931027 | 612413 | Crosby | 31 |
| 170267 | 958827 | Dolliver | 1 |
| 958827 | 170267 | Dolliver | 1 |
| 104131 | 707536 | Dolliver | 14 |
| 707536 | 104131 | Dolliver | 14 |
| 477801 | 505241 | Dolliver | 8 |
| 505241 | 477801 | Dolliver | 8 |
| 118199 | 824292 | Kendrick | 1A |
| 824292 | 118199 | Kendrick | 1A |
| 105540 | 231742 | Kendrick | 3B |
| 231742 | 105540 | Kendrick | 3B |
+--------+--------+----------+------+
谁能告诉我为什么?
【问题讨论】:
-
我非常怀疑
a.id > b.id和a.id < b.id产生了相同的结果。如果他们这样做了,那不是问题吗?您的示例输出很明显是a.id > b.id的结果,所以我建议您再次运行a.id < b.id版本,看看它会产生不同的结果。!=的输出看起来像是这两者的组合,这正是我所期望的。 -
在 SQL 中,“不等于”运算符是“”,而不是“!=”。你试过“”吗?
-
@MikeNakis that's fine syntax for Postgres
-
@JNevill 哦,很有趣。谢谢。
-
您得到的结果与预期的一样,只是前两个结果不完全相同。如果您注意前两列,您会发现在比较前两个结果时它们被交换了。如果你能确认是这样的话,你也会更好地理解第三个输出。