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

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Pionas
  • 346
  • 1
  • 4
  • 15
  • 1
    why do you want to change it? – Makudex Sep 08 '15 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 – Pionas Sep 08 '15 at 10:34

1 Answers1

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!

Community
  • 1
  • 1
Makudex
  • 1,042
  • 4
  • 15
  • 40