0

我有 3 张桌子

tblMarkers tblReviews tblImages

我想从 tblMarkers 返回所有记录以及每个标记的所有评论和图像的计数。更复杂的是,它应该返回已知点半径内的所有标记。

所以预期的结果是

MarkerID-MarkerName-ReviewCount-ImageCount

1223-SomeName-0-1

这是我到目前为止所拥有的,这会返回评论数,但我无法获得正确的 SQL 来添加图像数

SELECT
`tblMarkers`.`ID`,
`tblMarkers`.`Type`,
`tblMarkers`.`Name`,
`tblMarkers`.`Latitude`,
`tblMarkers`.`Longitude`, 
(3959 * acos( cos( radians('45.1') ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians('6') ) + sin( radians('45.1') ) * sin( radians( Latitude ) ) ) )  
AS distance,
Count(`tblReviews`.`marker_id`) As reviewCount
FROM
`tblMarkers`
LEFT JOIN `tblReviews` ON `tblMarkers`.`ID` = `tblReviews`.`marker_id`
GROUP BY
`tblMarkers`.`ID`,
`tblMarkers`.`Type`,
`tblMarkers`.`Name`,
`tblMarkers`.`Latitude`,
`tblMarkers`.`Longitude`
HAVING
`distance` < '50'
ORDER BY
distance;

图片表结构为

ID [primaryKey] (same as tblMarkers.ID)
file
title

如何添加所有图像的计数?

4

2 回答 2

1

试试这个:

SELECT M.ID
    , M.Type
    , M.Name
    , M.Latitude
    , M.Longitude
    , (3959 * acos(cos(radians('45.1')) * cos(radians(M.Latitude )) * cos(radians(M.Longitude) - radians('6')) + sin(radians('45.1')) * sin(radians(M.Latitude ))))  AS distance
    , IFNULL(COUNT(DISTINCT R.review_id) , 0) AS ReviewCount
    , IFNULL(COUNT(DISTINCT I.ID), 0) AS ImageCount
    FROM tblMarkers AS M
    LEFT JOIN tblReviews AS R ON R.marker_id = M.ID
    LEFT JOIN tblImages AS I ON I.marker_id = M.ID
    GROUP BY M.ID, M.Type, M.Name, M.Latitude, M.Longitude
    HAVING distance < 50
    ORDER BY distance

我打赌你已经知道了LEFT JOIN。所以我曾经COUNT(DISTINCT R.review_id))计算所有不同的评论ID(只要确保它review_id是唯一的)。如果特定标记记录没有相应的评论和图像记录,我曾经IFNULL(XXX , 0)显示0.

我使用ALIASES使您的查询干净整洁。随意问。

于 2013-06-13T11:33:28.987 回答
0

如果图像表的 ID 字段是标记表 ID 字段的引用,则查询将是:

SELECT
`tblMarkers`.`ID`,
`tblMarkers`.`Type`,
`tblMarkers`.`Name`,
`tblMarkers`.`Latitude`,
`tblMarkers`.`Longitude`, 
(3959 * acos( cos( radians('45.1') ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians('6') ) + sin( radians('45.1') ) * sin( radians( Latitude ) ) ) )  
AS distance,
Count(`tblReviews`.`marker_id`) As reviewCount,
Count(`tblImage`.`ID`) As imageCount,
FROM
`tblMarkers`
LEFT JOIN `tblReviews` ON `tblMarkers`.`ID` = `tblReviews`.`marker_id`
LEFT JOIN `tblImage` ON `tblMarkers`.`ID` = `tblImages`.`ID`
GROUP BY
`tblMarkers`.`ID`,
`tblMarkers`.`Type`,
`tblMarkers`.`Name`,
`tblMarkers`.`Latitude`,
`tblMarkers`.`Longitude`
HAVING
`distance` < '50'
ORDER BY
distance;
于 2013-06-13T10:58:48.887 回答