sql - Select all elements from one column that have ONLY ONE value in an associated column -


i have following database

table id_a    1 2 3 4  table b id_b  id_o    1     2 2     2 3     2 4     5 5     8 6     2 7     5 8     1   table c id_a    id_b 1       3 1       2 3       6 2       8 4       4 4       7 

i want elements have associated 1 id_o table b, table c link between 2 tables. in case bring me

id_a  id_o 4     5 

since id_a=4 has associated records table b id_o=5

what tried was:

select   c.id_a, b.id_o   tablec c join   tableb b on   c.id_b = b.id_b group   c.id_a, b.id_o having   count(id_o) = 1; 

but doesn't return want @ all, doing wrong?

sql statement

select      ta.id_a,     tb.id_o tablea ta left join tablec tc on tc.id_a = ta.id_a left join tableb tb on tb.id_b = tc.id_b group      ta.id_a,     tb.id_o having count(tb.id_o) = 1; 

description of sql statement:

  • select records of tablea.
  • attach, e.g. join corresponding details tablec (link table)
  • attach, e.g. join corresponding details tableb
  • group tablea's id_a , tableb's id_o.
  • calculate number of id_os each group , filter results allowing ones having number of id_os equal 1.

results:

id_a    id_o ------------ 2       1 3       2 

notes:

  • i added tablea record (id_a = 5) without corresponding id_b or id_o.
  • alongside tablea details, can fetch tableb details (and tablec details) because filtered grouped records represent individual tablea records. condition group on each of fetched column. in other situations (like, example, when you'd use having count(tb.id_o) >= 1) not right fetch tableb (or tablec) details alongside tablea details, because results not correctly displayed.
  • i'd mention that, if you'd have said "select records tablec where...", have begun sql statement select ... tablec tc left join ..., conform definition of left join: left table fetched records, unconditionally. filter can afterwards applied.

used table structure

drop table if exists `tablea`; create table `tablea` (   `id_a` int(11) default null ) engine=innodb default charset=utf8;  drop table if exists `tableb`; create table `tableb` (   `id_b` int(11) default null,   `id_o` int(11) default null ) engine=innodb default charset=utf8;  drop table if exists `tablec`; create table `tablec` (   `id_a` int(11) default null,   `id_b` int(11) default null ) engine=innodb default charset=utf8; 

used table data

insert `tablea` (`id_a`) values (1), (2), (3), (4), (5);  insert `tableb` (`id_b`, `id_o`) values (1,2), (2,2), (3,2), (4,5), (5,8), (6,2), (7,5), (8,1);  insert `tablec` (`id_a`, `id_b`) values (1,3), (1,2), (3,6), (2,8), (4,4), (4,7); 

good luck.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -