如何改进此数据库查询?这需要太多时间

Mar*_*raz 4 mysql timestamp

查询是这样的:

$today = $date->getTimestamp();

SELECT t.*, u.screen_name, u.profile_image_url
  FROM table AS t 
  LEFT JOIN users AS u 
  ON t.user_id=u.id_str 
  WHERE UNIX_TIMESTAMP(t.created_at) > {$today}
  ORDER BY id DESC 
  LIMIT 12;
Run Code Online (Sandbox Code Playgroud)

a1e*_*x07 8

即使您没有在问题中发布表定义,因此我无法确定遗漏了什么,但以下索引将是有益的:

  1. 表上的索引(user_id,created_at)
  2. 用户索引(id_str)甚至用户索引(id_str,screen_name,profile_image_url)
  3. 我猜你已经在 table(id) 上有一个索引

更新

更改WHERE:从WHERE UNIX_TIMESTAMP(t.created_at) > {$today}WHERE t.created_at > FROM_UNIXTIME({$today}),这样优化器create_at将更有效地使用包含列的索引。