views:

38

answers:

1

I have two tables, one that stores serial number uut_build, and another for measurements that belong to the serial numbers measure_list, I'm trying to get the count of records in measure_list that belongs to a unique serial number.
Query #1

select id, uut_sn from uut_build where uut_sn like 'A%';

Query #2

select count(*) from measure_list as m WHERE m.uut_id = [result from query #1]

Is it possible to do this with just one query statement?

Thanks in advance!

+2  A: 

Use:

   SELECT ub.uut_sn,
          COALESCE(COUNT(ml.*), 0) AS cnt
     FROM UUT_BUILD ub
LEFT JOIN MEASURE_LIST ml ON ml.uut_id = ub.uut_sn
    WHERE ub.uut_sn LIKE 'A%'
 GROUP BY ub.uut_sn

It's a little unclear what columns link the two tables...

This will return all serial numbers - if they don't have a record in MEASURE_LIST, the cnt value will be zero. If you only want a list of records that have records in MEASURE_LIST, remove "LEFT" from the query I provided.

OMG Ponies
I suspect id on uut_build corresponds to uut_id on measure_list - otherwise, the desired output could be returned by querying measure_list only.
Mark Bannister
@Mark Bannister: Depends if the OP wants to get values from the `UUT_BUILD` table as well. And running the query on only the `MEASURE_LIST` table will only show serials that exist in the table - it would never show those who don't have supporting records in `MEASURE_LIST`.
OMG Ponies
@OMG: Yes - I was more concerned with the linkage field.
Mark Bannister
Thanks for the input and sorry for being unclear. The tables are related by the id field of uut_sn, which is part of the measrue_list. The suggestion above gave me enough lead-way to get the query to work. FYI, the final solution is:SELECT ub.uut_sn, COALESCE(COUNT(*), 0) AS cnt FROM uut_build as ub LEFT JOIN measure_list as ml ON ml.uut_id = ub.id WHERE ub.uut_sn LIKE 'A%' GROUP BY ub.uut_sn;
cfpete