mysql - SQL JOIN many-to-many -
sorry minimalistic title don't know how describe in short. have 3 tables:
the table of groups
id | genre ----------------- 1 | action 2 | adventure 3 | drama
many many table
groupid | elementid ----------------- 3 | 1 1 | 2 2 | 2 2 | 3 3 | 3
and table of elements
id | element ----------------- 1 | pride , prejudice 2 | alice in wonderland 3 | curious incident of dog in night time
all fine , simple. select trying achieve following
id | element | genre ------------------------------------------------------------- 1 | pride , prejudice | drama 2 | alice in wonderland | null 3 | curious incident of dog in night time | drama
i want select all elements table elements , set genre field drama or null.
i'm trying in mysql.
thank in advance
it's possible little trick (outer join on many-to-many table, constraint groupid has 3 (for drama)
http://sqlfiddle.com/#!2/b7c18/2
select elements.id, elements.element, groups.genre elements left outer join group_elements on elements.id = group_elements.elementid , group_elements.groupid = 3 left outer join groups on group_elements.groupid = groups.id
left outer join
means : take lines tables preceded (the ones on left hand side of left outer join
, if will), if there's no lines corresponding them in following tables. condition on elements.id = group_elements.elementid , group_elements.groupid = 3
says if find matches our elementid, must drama (groupid = 3). left outer join on groups table, enables display genre column, or null if element not drama.
Comments
Post a Comment