SQL : select unmatching records from 2 tables

标签 sql database postgresql join where-clause

我有 2 个表,我想从第一个表中检索 id_apartment 没有出现在第二个表中的行:

id | id_floor | id_apartment 
----+----------+--------------
  1 |        0 |          101
  2 |        1 |          101
  3 |        1 |          102
  4 |        1 |          103
  5 |        1 |          104
  6 |        2 |          201
  7 |        2 |          202
  8 |        2 |          203


table2.id | table2.guest | table2.apartment_id
----+---------------+--------------
  1 |         65652 |          101
  2 |         65653 |          101
  3 |         65654 |          101
  4 |         65655 |          101
  5 |         65659 |          102
  6 |         65656 |          201
  7 |         65660 |          202
  8 |         65661 |          202
  9 |         65662 |          202
 10 |         65663 |          203

预期输出:
floor | number
-------+--------
     1 |    103
     1 |    104

我尝试使用 LEFT、INNER 和 RIGHT 连接,但我总是得到 EMPTY 结果。我该如何管理?

最佳答案

您可以使用 not exists :

select *
from table1 t1
where not exists(
    select 1
    from table2 t2
    where t1.id_apartment = t2.apartment_id
)

关于SQL : select unmatching records from 2 tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60400001/

相关文章:

performance - 优化排除 PostgreSQL 中特定用户的触发器

php - 选择一列的所有值,按另一列排序

mysql - 搜索查询 - 邮政编码、公司名称或位置

php - 谁有好的 PHP 脚本可以作为 cronjob 运行来备份 MySQL 数据库?

java - 如何使用 Java 和 PostgreSQL 在 Web 应用程序中保存、检索和绘制图像?

postgresql - centos 中的 libpq 库

java - 使用 filereader 从文件中读取文本

php - 拆分两个不同数据库表中的多行

MySQL 性能 - CHAR(64) 与 VARCHAR(64)

database - 在 Oracle 10g R2 中显示 IP 地址的命令?