0

I'm running the following query to select all posts liked by a user. The problem is, it takes quite a few seconds for the page to load.

SELECT p.*, a.username, a.avatar FROM user_posts p
LEFT JOIN account a ON p.uid=a.id WHERE p.pid in
(select post from user_posts_likes where `by`='$user_id')
ORDER BY `pid` DESC LIMIT $npage, 10";

Is there a better way to do this instead of using WHERE IN?

Thanks.

2
  • 1
    Hard to say from here. Prefix the query with explain to get the plan, and add it to your question Commented Dec 28, 2013 at 22:27
  • Oh, I think it's pretty likely Commented Dec 28, 2013 at 22:34

1 Answer 1

3

You can try two joins like this:

SELECT p.*, a.username, a.avatar FROM user_post_likes l
JOIN post p ON l.post = p.pid
LEFT JOIN account a ON p.uid = a.id
WHERE l.by = 555

I deducted the foreign key names from your original query so they might be wrong. The 555 is an example user id, obviously.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.