在 SQL 语句中提示
Tip in a SQL statement
我有一个小项目,我需要显示用户尚未访问过的所有餐厅。我有 3 tables
RestaurantTable
PersonTable
VisitTable
Visit
table 是餐厅和有列的人的联接 table
id, person_id, restaurant_id, Date
我可以使用什么查询来return还没有访问过的餐厅?
请注意,如果访问了一家餐厅,它会被添加到 VisitTable
中,否则它不会被插入到 VisitTable
中。我正在使用 PostgreSQL。
假设RestaurantTable包含restaurant_id列,可以使用如下代码:
select restaurant_id from RestaurantTable
where restaurant_id not in (select distinct restaurant_id from VisitTable)
我会推荐 not exists
:
select *
from restaurants r
where not exists (select 1 from visits v where v.restaurant_id = r.restaurant_id)
为了性能,您需要 visits(restaurant_id)
上的索引;如果你有一个正确声明的外键,它应该已经存在了。
我有一个小项目,我需要显示用户尚未访问过的所有餐厅。我有 3 tables
RestaurantTable
PersonTable
VisitTable
Visit
table 是餐厅和有列的人的联接 table
id, person_id, restaurant_id, Date
我可以使用什么查询来return还没有访问过的餐厅?
请注意,如果访问了一家餐厅,它会被添加到 VisitTable
中,否则它不会被插入到 VisitTable
中。我正在使用 PostgreSQL。
假设RestaurantTable包含restaurant_id列,可以使用如下代码:
select restaurant_id from RestaurantTable
where restaurant_id not in (select distinct restaurant_id from VisitTable)
我会推荐 not exists
:
select *
from restaurants r
where not exists (select 1 from visits v where v.restaurant_id = r.restaurant_id)
为了性能,您需要 visits(restaurant_id)
上的索引;如果你有一个正确声明的外键,它应该已经存在了。