sql - SQL 语句中的提示
问题描述
我有一个小项目,我需要显示用户尚未访问的所有餐厅。我有 3 张桌子
RestaurantTable
PersonTable
VisitTable
Visit
table 是餐厅和人的连接表,有列
id, person_id, restaurant_id, Date
我可以使用什么查询来返回尚未访问的餐厅?
请注意,如果访问了餐厅,则会将其添加到 .VisitTable
否则不会插入到VisitTable
. 我正在使用 PostgreSQL。
解决方案
我会推荐not exists
:
select *
from restaurants r
where not exists (select 1 from visits v where v.restaurant_id = r.restaurant_id)
为了性能,您需要一个索引visits(restaurant_id)
; 如果你有一个正确声明的外键,它应该已经存在。
推荐阅读
- javascript - 添加到具有可变深度的嵌套对象
- javascript - TypeError:在制作自定义选择框/下拉列表时无法读取未定义的属性“项目”
- elasticsearch - 如何在 Elasticsearch 中聚合聚合的结果?
- python - 正确地将 JSON 转换为 CSV 格式?
- php - 为什么 $_POST 方法没有得到输入框的值?
- restful-authentication - act_like_restful_authentication 与 authlogic v5
- regex - 如何使用 sed 将单个转义字符替换为双精度字符
- python - 如何制作像甜甜圈图一样的时间
- javascript - ESLint 规则在 Angular 中排除某些关键字和短语?
- php - Php - 超过超时时停止线程