Search code examples
mysqlsqljoinwhere-in

Split a mysql query into two to avoid a join -> sum ids and use where in


What is faster:

Using a join to get userdetails for posts or only get the post data which includes the userid, collect the userIDs and after the posts are queried run one:

SELECT x,y,z FROM users WHERE id in (1,2,3,4,5,6,7...etc.)

Short:

What is better?:

SELECT x,y,z,userid 
FROM posts 
WHERE id > x 
ORDER BY id
LIMIT 20

SELECT x,y,z 
FROM users 
WHERE id IN (1,2,3,4,5,6,7...etc.)

or:

SELECT p.x,p.y,p.z, u.username,u.useretc,u.user.etc 
FROM posts p 
INNER JOIN users u 
ON u.id = p.userid 
AND id > n 
ORDER BY id
LIMIT 20

In some scenarios this could reduce the querying of the user table to 2 instead of 20 times. A page in a discussion where only two user posted.


Solution

  • anyway the second way is better:

    1. You have only one call to database instead of two - so the channel between your DB and Application server is less loaded
    2. Second way usually should be faster and less memory consuming because analyser can decide better how to manage its resources (it has all the requirements in one query)
    3. In first example you force database to use not-cached queries (second query of the first example is not constant because in-list has different amount of inputs) so it parses the second query more often which leads to performance losses