繁体   English   中英

如何在Laravel中使用联接子查询

[英]How to do this in Laravel, subquery with join

我正在使用Laravel 4重做我的网站。 最困难的部分是将我的查询转换为查询生成器/口才格式。 如果有人可以帮助我得到这个最长的一个,我将万分感谢!

SELECT zipcode, city, state, lat, lng, distance_in_mi
FROM (
SELECT zipcode, city, state, lat, lng, r, ( 3963.17 * ACOS( COS( RADIANS( latpoint ) ) * COS(     RADIANS( lat ) ) * COS( RADIANS( longpoint ) - RADIANS( lng ) ) + SIN( RADIANS( latpoint ) ) * SIN( RADIANS( lat ) ) ) ) AS distance_in_mi
FROM zipcode
JOIN (
SELECT $current_lat AS latpoint, $current_lng AS longpoint, 10 AS r
) AS p
WHERE lat
BETWEEN latpoint - ( r /69 ) 
AND latpoint + ( r /69 ) 
AND lng
BETWEEN longpoint - ( r / ( 69 * COS( RADIANS( latpoint ) ) ) ) 
AND longpoint + ( r / ( 69 * COS( RADIANS( latpoint ) ) ) )
) d
WHERE distance_in_mi <= r
ORDER BY distance_in_mi

最近尝试:

$data_object = DB::table('zipcode', function($query)
            {
        $query->select('zipcode, city, state, lat, lng, r, ( 3963.17 * ACOS( COS( RADIANS( latpoint     ) ) * COS( RADIANS( lat ) ) * COS( RADIANS( longpoint ) - RADIANS( lng ) ) + SIN( RADIANS( latpoint ) )     * SIN( RADIANS( lat ) ) ) ) AS distance_in_mi')
          ->from('zipcode')
          ->join('zipcode', function($query1)
            {
            $query1->select("($current_lat AS latpoint, $current_lng AS longpoint, 10 AS r) AS p")
                    ->whereBetween('lat', 'latpoint - ( r /69 )' )
                    ->whereBetween('lng', 'longpoint - ( r / ( 69 * COS( RADIANS( latpoint ) ) ) )     AND longpoint + ( r / ( 69 * COS( RADIANS( latpoint ) ) ) )' );

            })
            })
                    ->where('distance_in_mi', '<=', 'r')
                    ->orderBy('distance_in_mi')
                    ->get();

您不需要联接和子选择。 那是应该为您工作的:

DB::table('zipcode')
->select(['zipcode','city','state','lat','lang',
    DB::raw("(3963.17*ACOS(COS(RADIANS(latpoint))*COS(RADIANS(lat))*COS(RADIANS(longpoint)-RADIANS(lng))+SIN(RADIANS(latpoint))*SIN(RADIANS(lat)))) 
        AS distance_in_mi, $current_lat AS latpoint, $current_lng AS longpoint, 10 AS r")])
->orderBy('distance_in_mi')
->havingRaw('lat BETWEEN latpoint - (r/69)
    AND latpoint + (r/69)
    AND 
    lng BETWEEN longpoint - (r/(69*COS(RADIANS(latpoint))))
    AND longpoint + (r/(69*COS(RADIANS(latpoint))))
    AND distance_in_mi <= r')
->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM