What is optimal MySQL statement to select rows from same table that have some ids but not others? -


we need select segments_id, em_id following table mytable have segments_id of 5 or 8 not 1 or 7. clearer after comments made below, result set includes rows of segments_id, em_id em_id has segments_id of 5 or 8 not 1 or 7.

 +-------------+-------+  | segments_id | em_id |  +-------------+-------+  |    1        |   8   |  |    1        |  17   |  |    5        |   2   |  |    5        |   4   |  |    5        |   5   |  |    5        |  16   |  |    5        |  17   |  |    7        |   4   |  |    7        |   5   |  |    7        |   8   |  |    7        |  16   |  |    8        |   4   |  |    8        |   6   |  |    8        |   8   |  |    8        |  18   |  |    18       |   6   |  |    18       |  99   |  +-------------+-------+ 

the result should be:

 +-------------+-------+  | segments_id | em_id |  +-------------+-------+  |    5        |   2   |  |    8        |   6   |  |    8        |  16   |  +-------------+-------+ 

we need avoid using in clause because can scale millions of rows.

i understand involve join on and/or subquery i'm not seeing it. saw post stackoverflow: selecting rows table have same value 1 field cannot see solution.

you can use left join eliminate em_id has segment_id 1 or 7:

select m.segments_id, m.em_id mytable m left join (select * mytable (segments_id=1 or segments_id=7)) n on m.em_id=n.em_id n.segments_id null group m.em_id; 

see sqlfiddle here.

if 5 , 8 want keep , rest should eliminated, can tweak 1 of where clauses this:

select m.segments_id, m.em_id mytable m left join (select * mytable not (segments_id=5 or segments_id=8)) n on m.em_id=n.em_id n.segments_id null group m.em_id; 

sqlfiddle second query here.

and if 5 , 8 want keep , 1 , 7 want eliminate, can use (however in case, answer given @lad2025 might better choice):

select m.segments_id, m.em_id mytable m left join (select * mytable (segments_id=1 or segments_id=7)) n on m.em_id=n.em_id (n.segments_id null , (m.segments_id=5 or m.segments_id=8)) group m.em_id; 

pls. check third sqlfiddle improved set here.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -