SQL - 返回彼此不 'vice versa' 的所有行

SQL - Returning all rows that are not 'vice versa' of one another

我遇到了如下情况(请注意,此设置是作为最小可重现示例创建的)。我有 table 个房子,是这样创建的:

CREATE TABLE houses (
    id character varying(24) NOT NULL,
);

我有一个很大的 table 叫做 house_listings,像这样:

CREATE TABLE house_listings(
    id character varying(24) NOT NULL,
    house_one character varying(24) NOT NULL,
    house_two character varying(24) NOT NULL,
    for_sale bit NOT NULL,
    PRIMARY KEY (house_one, house_two),
    FOREIGN KEY (house_one) REFERENCES houses(id),
    FOREIGN KEY (house_two) REFERENCES houses(id)
);

所以,假设我 运行 以下查询:

select * from house_listings where house_one = '12345';

我得到以下输出:

+------------------------+------------------------+-------------------+--------------+
| id                     | house_one              | house_two         | for_sale     |
+------------------------+------------------------+-------------------+--------------+
| 9RV3fyeJuUbAsHYdAb2Qnm | 12345                  | 8888              | 0x00         |
+------------------------+------------------------+-------------------+--------------+

然后我 运行 以下查询:

select * from house_listings where house_two = '12345' 我得到以下结果:

+------------------------+-------------------+------------------------+--------------+
| id                     | house_one         | house_two              | for_sale     |
+------------------------+-------------------+------------------------+--------------+
| 1oFH1oDkLyng6ZHNafqcXr | 8888              | 12345                  | 0x00         |
| vW4eNAC7jgZVxWAGxH4xAR | 7777              | 12345                  | 0x00         |
+------------------------+-------------------+------------------------+--------------+

注意这个结果的第一行如何以某种相反的方式对应于另一个结果的第一行(即在这种情况下 house_one 和 house_two 被翻转)。

不过,我感兴趣的是这个结果的第二行。其中 house_one 是 7777,house_two 和 12345。

我想以某种方式 运行 一个基本上 return 所有行都像第二行的查询。所以,给定一个特定的房屋 ID,比如 12345,它只会 return (在这个例子中):

+------------------------+-------------------+------------------------+--------------+
| id                     | house_one         | house_two              | for_sale     |
+------------------------+-------------------+------------------------+--------------+
| vW4eNAC7jgZVxWAGxH4xAR | 7777              | 12345                  | 0x00         |
+------------------------+-------------------+------------------------+--------------+

我一直在这里试验自连接,因为我认为这可能是最好的方法,但是在 house_one = house_two 处连接的东西并不是我想要的,并且我不确定如何最好地解决这个问题。

如有任何帮助,将不胜感激!

您可以使用 not exists:

select hl.*
from house_listings hl
where not exists (select 1
                  from house_listings hl2
                  where hl2.house_one = hl1.house_two and
                        hl2.house_two = hl1.house_one
                 );

这returns都是这样的单身人士。当然,您可以将 where 子句添加到外部查询以限制为特定值 house_one.