转换' WITH CTE' MSSQL到MySQL

时间:2015-03-18 02:18:30

标签: mysql sql-server common-table-expression

我意识到这不会直接从MSSQL转换为MySQL,但我不确定如何使它工作。感谢您的任何帮助。

;WITH cte As (
SELECT
    post_id,
    status, 
    dealer, 
    distributor,
    SUM( 
        3959 * acos( 
        cos( radians(%f) ) * 
        cos( radians( lat ) ) * 
        cos( radians( lng ) - radians(%f) ) + 
        sin( radians(%f) ) * 
        sin( radians( lat ) ) 
        ) 
    ) 
    AS DISTANCE
    FROM wp_geodatastore
    GROUP BY post_id, status, dealer, distributor       
)
SELECT post_id, status, dealer, distributor, DISTANCE
FROM cte WHERE (DISTANCE < %d) 
AND status = 'publish' AND dealer = 'on' AND distributor = 'on'
ORDER BY DISTANCE
OFFSET %d ROWS
FETCH NEXT %d ROWS ONLY;

1 个答案:

答案 0 :(得分:1)

只需将其作为子查询:

SELECT post_id, status, dealer, distributor, DISTANCE
FROM (SELECT post_id, status, dealer, distributor,
             SUM( 3959 * acos( 
                 cos( radians(%f) ) * 
                 cos( radians( lat ) ) * 
                 cos( radians( lng ) - radians(%f) ) + 
                 sin( radians(%f) ) * 
                 sin( radians( lat ) ) 
                ) 
               ) AS DISTANCE
      FROM wp_geodatastore
      GROUP BY post_id, status, dealer, distributor       
     ) cte
WHERE (DISTANCE < %d) AND
      status = 'publish' AND dealer = 'on' AND distributor = 'on'
ORDER BY DISTANCE
OFFSET %d ROWS
FETCH NEXT %d ROWS ONLY;