我有这个查询,它显示了一些属性,并从另一个表中计算对它的引用数量:
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'
作出反应,显然你不能过滤子查询指定的名称?
如何实现目标?
答案 0 :(得分: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
答案 1 :(得分: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 ;
答案 2 :(得分: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
答案 3 :(得分: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;
OR
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;
答案 4 :(得分: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'