0

我有这个查询,它显示一些属性并计算从另一个表中对其的引用数:

SELECT 
       p.id,p.propName
       (
         SELECT COUNT(*) FROM propLoc WHERE propLoc.propID = p.id
       ) AS number
FROM property as p 
WHERE p.category != 'natural'

这会生成一个包含我要过滤的所有信息的好表:

id | propName | number
3  | Name 1   | 3
4  | Name 2   | 1
5  | Name 3   | 0
6  | Name 4   | 10
etc etc

我现在想过滤掉数字 <= 0 的属性所以我尝试添加一个AND number > 0但它Unknown column 'number' in 'where clause'显然会做出反应,你不能过滤子查询指定的名称?

我怎样才能实现我的目标?

4

5 回答 5

2

试试这个::

SELECT 
       p.id,p.propName, count(1) as number
FROM property as p 
inner join propLoc on (propLoc.propID = p.id)
WHERE p.category != 'natural'
group BY p.id
于 2012-07-11T09:08:08.920 回答
2

您拥有的内联子查询与LEFT JOIN. 将您的查询重写为 Join,并使其成为INNER一个。无论是这种方式:

SELECT p.id
     , p.propName
     , grp.number
FROM property AS p 
  INNER JOIN 
     ( SELECT propID 
            , COUNT(*) AS number
       FROM propLoc
       GROUP BY propID
     ) AS grp 
    ON grp.propID = p.id
WHERE p.category <> 'natural' ;

或这个:

SELECT p.id
     , p.propName
     , COUNT(*) AS number
FROM property AS p 
  INNER JOIN propLoc 
    ON propLoc.propID = p.id
WHERE p.category <> 'natural' 
GROUP BY p.id ;
于 2012-07-11T09:12:16.253 回答
2

WHERE不工作时,经常HAVNING工作,因为它稍后在链中过滤结果

SELECT 
       p.id,p.propName
       (
         SELECT COUNT(*) FROM propLoc WHERE propLoc.propID = p.id
       ) AS number
FROM property as p 
WHERE p.category != 'natural'
HAVING number > 0
于 2012-07-11T09:13:52.010 回答
0
SELECT p.id,p.propName,count(p.id) as number
FROM property as p 
inner join propLoc prop WHERE prop.propID = p.id
WHERE p.category != 'natural'
group p.id;

或者

SELECT p.id,p.propName,count(p.id) as number
FROM property as p 
left join propLoc prop WHERE prop.propID = p.id
WHERE p.category != 'natural' and number > 0
group p.id;
于 2012-07-11T09:11:20.950 回答
0
SELECT 
       p.id,p.propName,q.number
       from
       (
         SELECT propID,COUNT(*) as number FROM propLoc WHERE propLoc.propID = p.id
       ) q join
 property as p 
on q.propID=p.id
 where p.category != 'natural'
于 2012-07-11T09:17:22.857 回答