distinct - MYSQL issue howto count result in master table not including all rows from a Detail table "labels" used in a join -


to simplify question using few field in test table example

master db

id  description type  cost '1', 'test1', '2', '100' '2', 'test2', '2', '100' '3', 'test3', '3', '100' '4', 'test4', '4', '100' 

labels db

 id     name     masterid '1', 'label1', '1' '2', 'label1', '2' '3', 'label2', '1' '4', 'label3', '1' 

i count id's , make summary cost field records in master containing label1 , label2 labels

my query

select  count(distinct m.id) andtall , sum(m.cost) cost  master m    join labels l on  l.masterid=m.id , l.name in ('label1','label2') 

since using distinct in count result correct, cost wrong it's containg 3 records not 2.

'2', '300' return 200 since 2 records master table should returned.

try this

select     count( m.id ) andtall,   sum( m.cost ) cost  master m  join (      select        masterid            labels l            l.name in ('label1', 'label2')      group master_id ) l on l.masterid = m.id  

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -