PostgreSQL明显,分组,有一个?

时间:2011-06-15 14:07:59

标签: sql database postgresql group-by distinct-on

我在使用PostgreSQL查询时遇到了一些麻烦

我想要的是一个“广告系列”列表,按距离排序,距离某个位置的最小距离[in_lat,in_lng,in_radius] 现在,我正在检索距离(使用distance_in_km(...))两次。一旦订购,一次检查广告系列是否在我偏好的范围内。

此外,广告系列可能有多个“广告系列接收者”条目(receivetype [EMAIL,WEBSITE等...])

我想只检索一次广告系列。因此DISTINCT ON。

所以问题是,我怎样才能获得像“WHERE distance< in_radius”那样的工作时间。 我的猜测是增加了一个GROUP BY和HAVING,但我做了一些测试而没有得到工作。

任何帮助都得到了极大的赞赏!!!

    SELECT DISTINCT ON (c.campaign_uuid, distance)
            c.campaign_uuid,
            prl.lat,
            prl.long,
            distance_in_km(prl.lat, prl.long, in_lat, in_lng) AS distance                
        FROM 
            usercampaignrelations AS ucr
        LEFT JOIN
            campaignreceivers AS cr
        ON
            ucr.usercampaign_uuid = cr.usercampaign_uuid
        LEFT JOIN
            campaigntargetgrouprelations AS ctg
        ON
            cr.campaigntargetgroup_uuid = ctg.campaigntargetgroup_uuid
        LEFT JOIN
            campaigns AS c
        ON
            ucr.campaign_uuid = c.campaign_uuid
        LEFT JOIN
            companycampaignrelations AS cc
        ON
            c.campaign_uuid = cc.campaign_uuid
        LEFT JOIN
            pointradiuslocations AS prl
        ON
            c.location_uuid = prl.location_uuid
        WHERE 
            ucr.user_uuid = in_user_uuid
        AND
            (cr.status = 'SENT' OR cr.status = 'RETRIEVED')
        AND
            distance_in_km(prl.lat, prl.long, in_latitude, in_longtitude) < in_radius
        ORDER BY
            distance
        LIMIT 
            in_limit

1 个答案:

答案 0 :(得分:1)

AFAIK,distance_in_km()只会被调用一次(每行),只要你使用相同的参数,因此WHERE和ORDER BY不再对它进行评估。