SQL Server中where条件的子查询
我对使用子查询时的SQL Server中where条件的子查询,sql,sql-server,Sql,Sql Server,我对使用子查询时的where条件参数有一些疑问 select id, name, (select count(*) from table2) count from table1 输出为 +----+-------------+-------+ | id | name | count | +----+-------------+-------+ | 1 | abc | 13 | | 2 | efg |
where
条件参数有一些疑问
select
id, name,
(select count(*) from table2) count
from
table1
输出为
+----+-------------+-------+
| id | name | count |
+----+-------------+-------+
| 1 | abc | 13 |
| 2 | efg | 15 |
+----+-------------+-------+
我想在如下条件下使用此计数:
select
id, name,
(select count(*) from table2) count
from
table1
where
count = 15
但我得到了这个错误:
错误1054(42S22):“where子句”中的未知列“count”
我不想在where子句中使用整个子查询。如何解决此问题?使用派生表:
select * from
(
select id,name, (select count(*) from table2) count from table1
) dt
where count = 15
此查询:
select id,name, (select count(*) from table2) as count
from table1
不返回指定的结果。我怎么知道?这两行的计数不同。如果这是查询,则计数将是相同的
对于给定的查询,显而易见的解决方案是将子查询移动到from
子句:
select t1.id, t1.name, t2.cnt
from table1 t1 cross join
(select count(*) as cnt from table2 t2) t2
where t2.cnt = 15;
但是,您的查询可能是一个相关子查询。在这种情况下,最好的解决方案是使用apply
(也可用于不相关的情况):
@拉努。谢谢您。
select t1.id, t1.name, t2.cnt
from table1 t1 outer apply
(select count(*) as cnt
from table2 t2
) t2
where t2.cnt = 15;