SQL 不存在后查询的加入结果
Joining result of SQL Query after not exists
前几天,我问了这个post:
基本设置是我有一个 table 房子,创建如下:
CREATE TABLE houses (
id character varying(24) NOT NULL,
bit is_nice 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)
);
我正在使用问题答案中建议的命令从两个 table 中提取数据:
select hl.*
from house_listings hl
where not exists (select 1
from house_listings hl2
where hl2.house_one = hl.house_two and
hl2.house_two = hl.house_one
);
我的问题是,在这之后我剩下一个table,例如:
+------------------------+-------------------+------------------------+--------------+
| id | house_one | house_two | for_sale |
+------------------------+-------------------+------------------------+--------------+
| vW4eNAC7jgZVxWAGxH4xAR | 7777 | 12345 | 0x00 |
+------------------------+-------------------+------------------------+--------------+
我的问题如下:有没有一种方法可以从该查询中仅获取 return 值,其中 house_one
的 is_nice
值为 true?我尝试用房屋连接整个查询的结果,但 SQL 一直抛出语法错误,所以这是需要在查询中更早而不是更晚完成的事情吗?
谢谢
您应该能够将此条件添加到外部查询:
select hl.*
from house_listings hl join
houses h
on hl.house_one = h.id
where h.is_nice = 1 and
not exists (select 1
from house_listings hl2
where hl2.house_one = hl.house_two and
hl2.house_two = hl.house_one
);
前几天,我问了这个post:
基本设置是我有一个 table 房子,创建如下:
CREATE TABLE houses (
id character varying(24) NOT NULL,
bit is_nice 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)
);
我正在使用问题答案中建议的命令从两个 table 中提取数据:
select hl.*
from house_listings hl
where not exists (select 1
from house_listings hl2
where hl2.house_one = hl.house_two and
hl2.house_two = hl.house_one
);
我的问题是,在这之后我剩下一个table,例如:
+------------------------+-------------------+------------------------+--------------+
| id | house_one | house_two | for_sale |
+------------------------+-------------------+------------------------+--------------+
| vW4eNAC7jgZVxWAGxH4xAR | 7777 | 12345 | 0x00 |
+------------------------+-------------------+------------------------+--------------+
我的问题如下:有没有一种方法可以从该查询中仅获取 return 值,其中 house_one
的 is_nice
值为 true?我尝试用房屋连接整个查询的结果,但 SQL 一直抛出语法错误,所以这是需要在查询中更早而不是更晚完成的事情吗?
谢谢
您应该能够将此条件添加到外部查询:
select hl.*
from house_listings hl join
houses h
on hl.house_one = h.id
where h.is_nice = 1 and
not exists (select 1
from house_listings hl2
where hl2.house_one = hl.house_two and
hl2.house_two = hl.house_one
);