0

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

我的代码看起来像这样。

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

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

有没有人可以帮助我,我非常需要解决这个问题,我感谢每一个帮助。

提前致谢。

4

4 回答 4

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
于 2012-07-13T06:30:34.200 回答
0

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

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

于 2012-07-13T06:05:33.703 回答
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
于 2012-07-13T06:02:49.153 回答
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 
于 2012-07-13T06:16:19.570 回答