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'sid_a,tableb'sid_o. - calculate number of
id_os each group , filter results allowing ones having number ofid_os equal 1.
results:
id_a id_o ------------ 2 1 3 2 notes:
- i added
tablearecord (id_a = 5) without correspondingid_borid_o. - alongside
tableadetails, can fetchtablebdetails (andtablecdetails) because filtered grouped records represent individualtablearecords. conditiongroupon each of fetched column. in other situations (like, example, when you'd usehaving count(tb.id_o) >= 1) not right fetchtableb(ortablec) details alongsidetableadetails, because results not correctly displayed. - i'd mention that, if you'd have said "select records
tablecwhere...", have begun sql statementselect ... tablec tc left join ..., conform definition ofleft 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
Post a Comment