繁体   English   中英

带有count(*)的子查询

[英]Sub-query with count(*)

如何从子查询count(*)数据中获取与left(number,7)相关联的失败数据?

例如,我这样做:

SELECT * FROM table1 WHERE outcome = 'Fail' AND left(number,7) = 
   (SELECT count(*) as total, left(number,7) as prefix  
   FROM table1 where outcome like '%Passed%' 
   group by prefix order by total desc limit 250)

这将无法工作,因为子查询中有两个字段..那么如何解决呢?

您可以使用JOIN代替子查询:

SELECT t1.*, t2.total, ... 
FROM table1 AS t1
INNER JOIN
(
    SELECT count(*) as total, left(number,7) as prefix  
    FROM table1 
    where outcome like '%Passed%' AND outcome = 'Fail'
    group by prefix 
    order by total desc limit 250
) AS t2 ON t2.prefix = left(t1.number,7)

试试这个查询

 SELECT * 
 FROM 
   table1 a 
 INNER JOIN 
   (SELECT 
      count(*) as total, 
      left(number,7) as prefix  
   FROM 
      table1 
   where 
      outcome like '%Passed%' 
   group by 
      prefix 
   order by 
      total desc limit 250)b
 ON 
   a.outcome = 'Fail' AND 
   left(number,7) = b.prefix

暂无
暂无

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

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