0

I need to check that two columns both appear in a list of IDs. So right now I have this:

SELECT 
    `main_table`.*
FROM
    `activities` AS `main_table`
WHERE
    (actor_id IN ('10027' , '11535'))
        AND (original_actor_id IN ('10027' , '11535'))

The problem is that the list of IDs can get pretty big; into the thousands. I can't find a way without another temp table that lets me check that two columns are in a list without defining the list twice. I'm concerned that it's an excessively large query to send back and forth from my PHP web server.

3
  • so the problem with this approach is only the package size?
    – Masoud
    Commented Aug 4, 2015 at 3:10
  • That's the one that I'm worried about. However, anything suggestions to make these kinds of queries run faster when searching a long list multiple times would be appreciated.
    – user41527
    Commented Aug 4, 2015 at 3:12
  • U can make the size smaller by using a variable to hold the list. but if the list gets too large, you might pass the max_allowed_packet
    – Masoud
    Commented Aug 4, 2015 at 3:19

1 Answer 1

2

You can create a temp table, insert your parameters there and then join it:

create temporary table tmp (x int);
insert into tmp(x) values (10027),(11535);
select x.* 
from activities as x 
join tmp as y 
    on y.x = x.actor_id
join tmp as z
    on z.x = x.original_actor_id;
3
  • The OP's query has AND. It should be 2 joins to the temp table. Commented Aug 4, 2015 at 9:52
  • Oh, I missed that. I'll fix that when I get back to a computer. Commented Aug 4, 2015 at 9:55
  • Declaring a PK on tmp may help performance and insert in order of the the PK.
    – paparazzo
    Commented Aug 4, 2015 at 15:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.