sql - A MYSQL query limited to one enum type excluding others -


i'm having trouble wrapping head around query.

my table structure looks so:

submitted_name   type             user_submitted_id   submitted_id red              manager          1                       10 red              sales            1                       11 red                            1                       12 green                          2                       13 green            sales            2                       14 blue             sales            3                       15 yellow           sales            4                       16 aqua blue        manager          1                       17 lime green       manager          1                       18 lime green       sales            1                       19 

how write query show me submitted_names have type "sales" , no other types. type enum data type. names not unique.

submitted_name not indexed column , database has 15 million rows.

so given test data, result should

`blue | sales | 2` 'yellow | sales | 4' 

i've tried doing distincts , group by's/havings keep drawing blank on how structure this. know isn't complicated question, it's been awhile since i've done sql queries , couldn't figure out best approach "googling" this.

select t1.* my_table t1    left join my_table t2       on t1.submitted_name = t2.submitted_name , t1.type != t2.type    t1.type='sales' , t2.type null 

this finds records in my_table have type=sales, , no record same submitted_name exist having different type.

edit: alternative approach:

select submitted_name,group_concat(`type`) `type`,group_concat(`id`) `id` my_table group submitted_name having `type`='sales' 

what - take records , group them submitted_name, filter them ones having single type "sales".

i can't promise have huge performance boost given table size (or have boost @ all, since there full-scan on 12m records table anyway), @ least there not join.

edit2: given new information, idea use indexed column (user_submitted_id) instead of submitted_name joins/group by, in both scenarios.

the first query this:

select t1.* my_table t1    left join my_table t2       on t1.user_submitted_id = t2.user_submitted_id , t1.type != t2.type    t1.type='sales' , t2.type null 

nb: note idea specify exact columns in query instead of t.*, decrease memory consumption result set, , may result in performance gain.

and second query this:

select submitted_name,group_concat(`type`) `type`,group_concat(`id`) `id` my_table group user_submitted_id having `type`='sales' 

Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -