使用子查询中的计数来确定行是否应包含在结果行中

Using count from subquery to determine if row should be included in result rows

我正在构建一个网站,我需要使用 gps 坐标根据邻近度向 return 用户查询,但前提是用户也有一张标记为私人的照片。照片 table 称为 'photos',照片所属的标识符是 user_id 列。每个用户的用户 table 中也存在相同的列名。我想做的是使用子查询来查看用户是否在照片 table 中有任何标记为私人 (private = 1) 的照片,如果有,return 该用户和一些基本信息。

出于某种原因,我的查询无法正常工作,我已经为此苦苦挣扎了很长一段时间。任何帮助将不胜感激!

这是我构建的查询,但它不起作用。我也尝试了许多其他查询。

SELECT users.user_id, 
       users.display, 
       users.lat, 
       users.lng, 
       users.featured, 
       profile.type, 
       profile.user_id, 
       ( 3959 * Acos(Cos(Radians('41.6032207')) * Cos(Radians(users.lat)) * Cos( 
                                   Radians(users.lng) - Radians('-73.087749')) + 
                              Sin(Radians('41.6032207')) * Sin( 
                              Radians(users.lat))) ) 
                              AS distance, 
       Count(photos.photo_id) 'Photo Count' 
FROM   users, 
       profile 
       INNER JOIN photos 
               ON users.user_id = photos.user_id 
                  AND photos.private = 1 
GROUP  BY users.user_id 
HAVING Count(photos.photo_id) > 0 
       AND users.account_type = '1' 
       AND profile.user_id = users.user_id 
       AND users.active = '1' 
       AND distance <= '10' 

您不应使用混合(显式和隐式)join 语法。您应该仅使用显式 join 语法并将 join 条件从 having 移至 where 子句:

  SELECT users.user_id, 
         users.display, 
         users.lat, 
         users.lng, 
         users.featured, 
         profile.type, 
         profile.user_id, 
         ( 3959 * Acos(Cos(Radians('41.6032207')) * Cos(Radians(users.lat)) * Cos( 
                                     Radians(users.lng) - Radians('-73.087749')) + 
                                Sin(Radians('41.6032207')) * Sin( 
                                Radians(users.lat))) ) 
                                AS distance, 
         Count(photos.photo_id) `Photo Count`
  FROM   users
  INNER JOIN profile ON profile.user_id = users.user_id 
  INNER JOIN photos ON users.user_id = photos.user_id 
      AND photos.private = 1 
  WHERE users.account_type = '1' 
    AND users.active = '1' 
  GROUP  BY users.user_id 
  HAVING Count(photos.photo_id) > 0 
    AND distance <= '10' 

并且您应该对复合列名称使用反引号(而不是单引号)