简体   繁体   中英

Count subquery from results of MySQL query

I don't know exactly how to explain this but I'm trying to get my second query optimized and write it properly.

This query is fast - 0.0005 seconds

select 
  wp_users.ID
from wp_users
  inner join wp_usermeta
    on wp_users.ID = wp_usermeta.user)id
where wp_usermeta.meta_value like '%user%'
limit 10

When I add this subquery it slows it down significantly - 5.4 seconds

select 
  wp_users.ID,
  (select count(*) from wp_postmeta where meta_key = wp_users.ID) as posts_read
from wp_users
  inner join wp_usermeta
    on wp_users.ID = wp_usermeta.user)id
where wp_usermeta.meta_value like '%user%'
limit 10

When I increase the limit the execution time goes up, of course. Is there a way to write it so it executes faster?

First thing to try is to put an index on wp_postmeta (meta_key) .

You can also try if left joining a derived table doing the aggregation once helps.

SELECT wp_users.id,
       coalesce(wp_postmeta.count, 0) posts_read
       FROM wp_users
            INNER JOIN wp_usermeta
                       ON wp_users.id = wp_usermeta.user_id
            LEFT JOIN (SELECT count(*) count,
                              wp_postmeta.meta_key
                              FROM wp_postmeta
                              GROUP BY wp_postmeta.meta_key) wp_postmeta
                      ON wp_postmeta.meta_key = wp_users.id
       WHERE wp_usermeta.meta_value LIKE '%user%'
       LIMIT 10;

An index on wp_users (id) is already there I guess. One on wp_usermeta (user_id, meta_value) might also help.

If possible you should not use LIKE against a wildcard at the begining of the string. So if possible use LIKE 'user%' instead or even = 'user...' (fill the ... with the right value).

wp_users isn't needed:

SELECT user_id,count(*) as posts_read
FROM wp_usermeta
JOIN wp_postmeta ON meta_key = user_id
WHERE meta_value LIKE '%user%'
GROUP BY user_id`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM