/ Published in: MySQL
                    
                                        
A guy asked me to reduce the query execution time. He is getting 10 results but the query had joins which makes it time consuming.
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
Original Query
$totalrows = 10;
$sql = "SELECT
posts.Tags as tags,
posts.OwnerUserId as postsid,
posts.Id as postid,
posts.Body as body,
posts.Title as title,
users.Id as userid,
users.DisplayName as usersname
FROM posts
JOIN users ON posts.OwnerUserId = users.Id
WHERE posts.Title != '' order by rand() asc limit " . $totalrows;
Modified Version
$totalrows = 10;
$sql = "SELECT
posts.Tags as tags,
posts.OwnerUserId as postsid,
posts.Id as postid,
posts.Body as body,
posts.Title as title,
users.Id as userid,
users.DisplayName as usersname
FROM posts
JOIN users ON posts.OwnerUserId = users.Id
JOIN (select posts.id from posts where posts.title != '' order by rand() asc limit " . $totalrows .") AS tmp_result
ON (posts.Id = tmp_result.Id)";
Comments
 Subscribe to comments
                    Subscribe to comments
                
                