【发布时间】:2018-05-09 08:56:52
【问题描述】:
我有两张桌子:
餐厅和调查邀请。
一家餐厅有很多调查邀请。
我想选择所有收到调查邀请且状态为“已批准”、“已完成”、“隐藏评论”的餐厅。
餐馆表有约 1400 行,调查邀请约 240 万行。
这是我的查询
SELECT `Restaurant`.`id`
FROM `restaurants` AS `Restaurant`
RIGHT JOIN `survey_invitations` AS `SurveyInvitations`
ON ( `SurveyInvitations`.`restaurant_id` = `Restaurant`.`id`
AND `SurveyInvitations`.`status`
IN (
'approved', 'completed', 'hidden_review'
)
)
WHERE `Restaurant`.`country_id` = 53
AND `Restaurant`.`area_id` IN ( 1, 16, 27, 118,
219, 221, 222, 223,
224, 225, 230, 231,
235, 236, 237, 238,
239, 240, 248, 226,
241, 244, 246, 227,
245, 228, 229, 242,
243, 249 )
group by `Restaurant`.`id`
这需要 1.235 秒。
运行解释给出
https://jsfiddle.net/bjuepb9j/3
我也试过了,但仍然没有运气 1.2 秒
SELECT `Restaurant`.`id`
FROM `db_portal`.`restaurants` AS `Restaurant`
RIGHT JOIN (
select `restaurant_id` from `survey_invitations` AS `SurveyInvitations`
where `SurveyInvitations`.`status`
IN ('approved', 'hidden_review', 'completed')
) AS `SurveyInvitations`
ON (
`SurveyInvitations`.`restaurant_id` = `Restaurant`.`id`
)
WHERE `Restaurant`.`country_id` = 53
AND `Restaurant`.`area_id` IN ( 1, 16, 27, 118,
219, 221, 222, 223,
224, 225, 230, 231,
235, 236, 237, 238,
239, 240, 248, 226,
241, 244, 246, 227,
245, 228, 229, 242,
243, 249 )
group by `Restaurant`.`id`
解释是一样的。
在小提琴中还有两个表上显示索引的结果。
我认为大约 240 万行需要 1.2 秒。 也许索引是错误的,我不太擅长这种东西。
编辑.1。 https://jsfiddle.net/bjuepb9j/6/
有 show create table 和 show columns ofsurvey_invitations
【问题讨论】:
-
你能分享你的带有索引和(主键/唯一键)的表创建语句吗?
-
你为什么使用
RIGHT JOIN?使用右连接,右连接条件上的表永远不会为空(因为 null 不等于 null),这意味着Restaurants表是可选的,但是您可以在where子句中通过执行来否定它针对Restaraunts表(country_id 和 area_id)进行相等性检查。我认为内部连接会更简单。尝试一下,看看它如何影响性能。 (内连接提供了更多优化选项)
标签: performance indexing mysql-5.7 right-join