在mysql中使用子查询的结果

时间:2012-07-13 05:55:09

标签: mysql subquery

如何在其父查询中使用子查询的结果?

我的代码看起来像这样。

select (select count(*) from tbl1 group by field) as result1, 
       (select count(*) from tbl2 group by field) as result2, 
       (select count(*) from tbl3 group by field) as result3,
       result1 + result2 - result3 as total1,
       result1 + result2  as total2 
 from tbl4 ;

有人建议直接添加子查询。

(select count(*)*....) as result1 + (select count(*)*....) as result2

但我认为它不想要我需要,bcoz我还需要在我的结果中显示/维护result1的值。

是否有人可以帮助我,我非常需要这项工作,我感谢你的每一个帮助。

提前谢谢。

4 个答案:

答案 0 :(得分:0)

您必须将查询包装在子选择中才能访问别名列名:

SELECT a.result1 + a.result2 - a.result3 AS total1,
       a.result1 + a.result2 AS total2
  FROM (
            select (select count(*) from tbl1 group by field) as result1, 
                   (select count(*) from tbl2 group by field) as result2,
                   (select count(*) from tbl3 group by field) as result3
       ) a

但这实际上是一个更好的解决方案:

    SELECT a.cnt + b.cnt - c.cnt AS total1, 
           a.cnt + b.cnt AS total2
      FROM (SELECT COUNT(*) cnt FROM tbl1 GROUP BY field) a
CROSS JOIN (SELECT COUNT(*) cnt FROM tbl2 GROUP BY field) b
CROSS JOIN (SELECT COUNT(*) cnt FROM tbl3 GROUP BY field) c

答案 1 :(得分:0)

假设您的子查询将返回一个集合。所以只需使用以下---

SELECT column1, column2, column3 FROM table1 WHERE column3 IN (SELECT column3 FROM table2 WHERE condition);

答案 2 :(得分:0)

select count1, count2, count3, 
  count1+count2-count3 as total1, count1+count2 as total2 
  from tbl4 
inner join 
  (select count(*) as count1,name from tbl1 group by name)as result1 
on tbl4.name=result1.name 
inner join 
   (select count(*)as count2,name from tbl2 group by name) as result2
on tbl4.name=result2.name 
inner join 
   (select count(*)as count3,name from tbl3 group by name) as result3
on tbl4.name=result3.name 

答案 3 :(得分:0)

请尝试此查询并告诉我

 select result1.cnt,result2.cnt,result2.cnt,result1.cnt + 
  result2.cnt - result3.cnt as total1,
  result1.cnt + result2.cnt  as total2   
  from
 (select field,COUNT(*) cnt from tbl1 group by field) as result1 
  join
 (select field,COUNT(*) cnt from tbl2 group by field) as result2
 on result1.field=result2.field
 join
 (select field,COUNT(*) cnt from tbl3 group by field) as result3
 on result3.field=result2.field
 join tbl4
 on tbl1.field = tbl4.field