首页 > 解决方案 > SQL 语句中的提示

问题描述

我有一个小项目,我需要显示用户尚未访问的所有餐厅。我有 3 张桌子

Visittable 是餐厅和人的连接表,有列

id, person_id, restaurant_id, Date

我可以使用什么查询来返回尚未访问的餐厅?

请注意,如果访问了餐厅,则会将其添加到 .VisitTable否则不会插入到VisitTable. 我正在使用 PostgreSQL。

标签: sqlpostgresqlsubquery

解决方案


我会推荐not exists

select *
from restaurants r
where not exists (select 1 from visits v where v.restaurant_id = r.restaurant_id)

为了性能,您需要一个索引visits(restaurant_id); 如果你有一个正确声明的外键,它应该已经存在。


推荐阅读