简体   繁体   English

编写MySQL子查询的更好方法

[英]Better way to write MySQL sub-query

I have two tables in my MySQL database: allele and locus . 我的MySQL数据库中有两个表: allelelocus I want to know for a given locus how many alleles there are and of those how many have the status Tentative . 我想知道一个给定的基因座有多少个等位基因,以及那些有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 您可以使用带有条件的sum的SUM()来产生布尔值1或0,因此它将为您提供条件的计数

  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: 使用WITH ROLLUP 修饰符将在末尾添加NULL状态,代表总数:

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. 如果您绝对不希望列出所有状态,则可以改为GROUP BY status = 'Tentative' (如果需要,可以选择WITH ROLLUP ),但是它不是可精简的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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