HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How can I improve this DB query? it takes too much time

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thiscanmuchquerytootimeimprovehowtakes

Problem

The query is this:

$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;

Solution

Even though you didn't post table definitions in your question so I can't tell for sure what is missed, the following indexes will be beneficial :

  • Index on table (user_id, created_at)



  • Index on users(id_str) or even users(id_str,screen_name,profile_image_url)



  • I guess you already have an index on table(id)



UPDATE

Change WHERE :
from WHERE UNIX_TIMESTAMP(t.created_at) > {$today} to WHERE t.created_at > FROM_UNIXTIME({$today}), this way optimizer will use index that includes create_at column more efficiently.

Context

StackExchange Database Administrators Q#29070, answer score: 8

Revisions (0)

No revisions yet.