【发布时间】:2018-11-01 19:20:45
【问题描述】:
我有 2 个表 customer 和 coupons,客户可能分配有也可能没有分配 reward_id,因此它是一个可为空的列。一个客户可以有很多优惠券,优惠券属于一个客户。
+-------------+------------+
| coupons | customers |
+-------------+------------+
| id | id |
| customer_id | first_name |
| code | reward_id |
+-------------+------------+
customer_id column is indexed
我想在 2 个表之间进行连接。
我的尝试是:
select c.*, cust.id as cust_id, cust.first_name as cust_name
from coupons c
join customer cust
on c.customer_id = cust.id and cust.reward_id is not null
但是,我认为reward_id 上没有索引,所以我应该在where 子句中移动cust.reward_id is not null:
select c.*, cust.id as cust_id, cust.first_name as cust_name
from coupons c
join customer cust
on c.customer_id = cust.id
where cust.reward_id is not null
我想知道第二次尝试是否会比第一次更有效率。
【问题讨论】:
-
创建缺失的索引而不是移动条件。优化器无论如何都会移动它们,如果它看到了它的好处。
-
@stickybit 假设
reward_id已编入索引,第二个查询会是更好的选择吗? -
@tkhuynh 。 . .他们应该有相同的执行计划。
-
两者都会产生完全相同的执行计划
-
@tkhuynh 。 . .这可能是由于缓存效应。或者如果差异非常小(比如
标签: sql postgresql performance inner-join