根据子查询结果进行过滤

时间:2017-11-15 12:07:30

标签: mysql database

我有mysql查询,我想基于gigcount进行过滤,当我使用where子句时,即gigcount = 0我得到错误未知列

SELECT
tbl_musicvenue.id AS id,

(SELECT

    COUNT(1)AS A1
    FROM
        smliveclaims AS Extent5
    WHERE
        Extent5.tbl_MusicVenueId = tbl_musicvenue.id and (Extent5.IsDeleted =0 or Extent5.IsDeleted is null)) AS gigcount

FROM

tbl_musicvenue

有没有办法让gigcount为0的所有项目

1 个答案:

答案 0 :(得分:0)

您可以将查询重写为

SELECT
a.id,
COUNT(b.tbl_MusicVenueId) gigcount
FROM
tbl_musicvenue a
LEFT JOIN smliveclaims b ON a.id = b.tbl_MusicVenueId AND (b.IsDeleted =0 OR b.IsDeleted IS NULL)
GROUP BY a.id
HAVING gigcount = 0

您的问题是在where子句中使用gigcount,其中可以用于查询中涉及的表的已知列。在您的情况下,gigcount是别名而不是预定义列,因此您无法在where子句中访问它。过滤这些列使用having子句