将行sql子查询转换为Codeigniter活动记录

时间:2018-09-05 07:01:07

标签: mysql sql codeigniter activerecord

我有一个运行良好的SQL。我想将其转换为活动记录查询,但不知道如何将这些子查询转换为活动记录

以下是我的sql:

Select A.*, B.*
FROM

( SELECT ( 6371 * acos( cos( radians(24.8964089) ) * cos( radians(RB.`lat`) ) 
   * cos( radians(RB.`lng`) - radians(67.06749)) + sin(radians(24.8964089)) 
   * sin( radians(RB.`lat`)))) AS distance, RB.`id` as BRID , R.`name` as NAME
FROM 
`rent_br` RB
JOIN `rent` R ON R.`id` = RB.`restId`
JOIN `rent_category` RC on R.`id` = RC.`restId`
WHERE 
TRUNCATE(RB.`lat`, 0) >= TRUNCATE(24.8964089,0)
AND TRUNCATE(RB.`lat`, 0) < TRUNCATE(25.8964089,0)
AND RB.`isdelivery` = '1'
AND RC.`catId` = 11
/*AND ( rent.`tags` like '%burger%' OR rent.`name` like '%burger%' OR info.`name` like '%burger%' )*/
HAVING 
`distance` <= 50
ORDER BY 
`distance` ASC ) A 

JOIN 

(select max(radius) as maxRadius, rent_br_delivery_radius.`rest_brId` as bbrId from `rent_br_delivery_radius`
group by bbrId) B on `A`.BRID = B.bbrId

WHERE A.distance <= B.maxRadius
ORDER BY A.NAME

1 个答案:

答案 0 :(得分:1)

您唯一需要考虑的就是使用query builder的{​​{3}}函数-一旦您了解了-这很容易。您只需要拆分查询并将它们合并到一个查询中

以下应完成工作

您的子选择

$strSubQuery = $this->db
    ->select('
        ( 6371 * acos( cos( radians(24.8964089) ) * cos( radians(RB.`lat`) ) 
       * cos( radians(RB.`lng`) - radians(67.06749)) + sin(radians(24.8964089)) 
       * sin( radians(RB.`lat`)))) AS distance, RB.`id` as BRID , R.`name` as NAME
      ')
    ->from('rent_br RB')
    ->join('rent r', 'r.id = RB.restId')
    ->join('rent_category RC', 'R.id = RC.restId')
    ->where('TRUNCATE(RB.`lat`, 0) >= TRUNCATE(24.8964089,0)', NULL, false)
    ->where('TRUNCATE(RB.`lat`, 0) < TRUNCATE(25.8964089,0)', NULL, false)
    ->where('RB.isdelivery`', 1)
    ->where('RC.catId', 11)
    ->having('distance <=', 50)
    ->order_by('distance', 'ASC')
    ->get_compiled_select();

您的子联接查询

$strSubQueryJoin = $this->db
    ->select_max('radius', 'maxRadius')
    ->select('rent_br_delivery_radius.rest_brId AS bbrId')
    ->from('rent_br_delivery_radius')
    ->group_by('bbrId')
    ->get_compiled_select();

最后我们将这些片段放在一起

$query = $this->db
    ->select('A.*, B.*')
    ->from($strSubQuery.' A', false)
    ->join('('.$strSubQueryJoin.') B', 'A.BRID = B.bbrId', 'INNER', false)
    ->where('A.distance <= B.maxRadius', NULL, false)
    ->order_by('A.NAME')
    ->get();

那应该可以完成工作。