简体   繁体   中英

Better way to write MySQL sub-query

I have two tables in my MySQL database: allele and locus . I want to know for a given locus how many alleles there are and of those how many have the status Tentative . I currently have the following query with subquery:

SELECT COUNT(*) as alleleCount,
     (SELECT COUNT(*) 
      FROM allele 
      INNER JOIN locus ON allele.LocusID = locus.PrimKey
      WHERE Status = 'Tentative'
      AND locus.ID = 762
      ) as newAlleleCount
FROM allele
INNER JOIN locus ON allele.LocusID = locus.PrimKey
WHERE locus.ID = 762

but I feel there must be a better way to write this query.

You can use SUM() using sum with condition will result in a boolean 1 or 0 so it will give you the count for your conditions

  SELECT locus.ID,COUNT(*) `all_alleles_per_locus`,
  SUM(Status = 'Tentative') `tentative_alleles_762`
  FROM allele 
  INNER JOIN locus ON allele.LocusID = locus.PrimKey
  GROUP BY locus.ID

One way would be to group the locus by its statuses and fetch each status's respective count; using the WITH ROLLUP modifier will add a NULL status at the end representing the total:

SELECT   status, COUNT(*)
FROM     allele JOIN locus ON locus.PrimKey = allele.LocusID
WHERE    locus.ID = 762
GROUP BY status WITH ROLLUP

If you absolutely do not want a list of all statuses, you can instead GROUP BY status = 'Tentative' (optionally WITH ROLLUP if desired)—but it will not be sargable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM