我有一個如下的情況(注意這個設定是作為一個最小的可重復的例子而創建的)。我有一個房屋表,是這樣創建的:
我有一個房屋表。
CREATE TABLE houses (
id character varying(24) NOT NULL,
);
我有一個叫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'/span>;
而我得到的輸出結果如下:
------------------------ ------------------------ ------------------- --------------
| 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。
我想以某種方式運行一個查詢,基本上可以回傳所有類似第二行的記錄。因此,給定一個特定的房子ID,比如12345,它將只回傳(在這個例子中):
------------------------ ------------------- ------------------------ --------------
| id | house_one | house_two | for_sale|
------------------------ ------------------- ------------------------ --------------
| vW4eNAC7jgZVxWAGxH4xAR | 7777 | 12345 | 0x00 |
------------------------ ------------------- ------------------------ --------------
我一直在嘗試使用自我連接,因為我認為這可能是最好的方法,但一些連接,其中house_one = house_two并不完全是我想要的,我不確定如何最好地處理這個問題。
希望得到任何幫助!
uj5u.com熱心網友回復:
你可以使用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
);
這將回傳所有這樣的單子。 當然,你可以在外層查詢中添加一個where子句,以限制到house_one的特定值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/320171.html
標籤:
