[Solved] What is the best way to select a few entries in a metas table?

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `users` ADD INDEX `users_idx_u_id` (`u_id`);
ALTER TABLE `users_metas` ADD INDEX `users_metas_idx_um_name_um_uid` (`um_name`,`um_uid`);
The optimized query:
SELECT
        u.u_nickname,
        u.u_email,
        um1.um_value AS u_avatar,
        um2.um_value AS u_connection 
    FROM
        users AS u 
    LEFT JOIN
        users_metas AS um1 
            ON um1.um_uid = u.u_id 
            AND um1.um_name = 'avatar' 
    LEFT JOIN
        users_metas AS um2 
            ON um2.um_uid = u.u_id 
            AND um2.um_name = 'connection_date' 
    WHERE
        u.u_id = :u_id

Related Articles



* original question posted on StackOverflow here.