0

How can I improve this query:

SELECT * FROM forum_thread WHERE
    thread_id not in (
        SELECT auth_id FROM forum_auth WHERE auth_group_id=1 and auth_type=2 and auth_visible=0
    )
    and thread_id in (
            SELECT thread_id FROM forum_thread WHERE
            category_id NOT IN (
                    SELECT auth_id FROM forum_auth WHERE auth_group_id=1 and auth_visible=0 and auth_type=1
            )
    )
ORDER BY last_post_id DESC limit 30

Thanks for answer

2
  • 1
    why do you want to change it? Commented Sep 8, 2015 at 10:30
  • This query is very complicated. I would like change it for something like that: ForumThread::whereNotIn('thread_id', {auth_id_array})->whereIn('thread_id', {thread_id_array})->orderBy('last_post_id', 'DESC')->limit(30)->get(); but i have a problem to create subquery in subquery Commented Sep 8, 2015 at 10:34

1 Answer 1

2

You can try this query for better performance:

SELECT * FROM forum_thread WHERE
thread_id NOT EXIST(
    SELECT auth_id FROM forum_auth WHERE auth_group_id=1 and auth_type=2 and auth_visible=0
)
and thread_id EXIST(
        SELECT thread_id FROM forum_thread WHERE
        category_id NOT EXIST(
                SELECT auth_id FROM forum_auth WHERE auth_group_id=1 and auth_visible=0 and auth_type=1
        )
)
ORDER BY last_post_id DESC limit 30

Just change NOT IN to NOT EXIST - see this link: NOT IN vs NOT EXISTS

and also change IN to EXIST - see also this link: Difference between EXISTS and IN in SQL?

Enjoy!

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

1 Comment

Thanks, i very helpful, but i still looking how change this query to laravel query builder

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.