加入CodeIgniter中的子查询

时间:2014-01-23 07:31:09

标签: codeigniter join subquery

我有以下mysql查询

SELECT
  events.id      AS id,
  A.sold_tickets
FROM (`events`)
  JOIN `category` AS cat
    ON `events`.`category_id` = `cat`.`id`
  JOIN `category` AS sub_cat
    ON `events`.`subCategoryID` = `sub_cat`.`id`
  JOIN `events_custom_dates` AS events_date
    ON `events_date`.`event_id` = `events`.`id`
  JOIN `my_promos`
    ON `events`.id = `my_promos`.`event_id`
  LEFT JOIN `mycalendar`
    ON `mycalendar`.`event_id` = `my_promos`.`event_id`
  LEFT JOIN `promo_events_stats`
    ON `promo_events_stats`.`id` = `events`.`id`
  LEFT JOIN (SELECT
           my_promos.event_id,
           SUM(tickets_sold.quantity) AS sold_tickets
         FROM my_promos
           JOIN tickets_sold
         ON tickets_sold.code = my_promos.link_code
         WHERE my_promos.user_id = '532'
         AND DATE(my_promos.date) >= '2013-11-01'
         AND DATE(my_promos.date) <= '2014-01-22'
         GROUP BY my_promos.event_id) A
    ON A.event_id = events.id
WHERE `my_promos`.`user_id` = '532'
    AND DATE(my_promos.date) >= '2013-11-01'
    AND DATE(my_promos.date) <= '2014-01-22'
GROUP BY my_promos.event_id

我想将包含子查询的连接部分转换为codeignitier方式。正在关注

LEFT JOIN (SELECT
       my_promos.event_id,
       SUM(tickets_sold.quantity) AS sold_tickets
     FROM my_promos
       JOIN tickets_sold
     ON tickets_sold.code = my_promos.link_code
     WHERE my_promos.user_id = '532'
     AND DATE(my_promos.date) >= '2013-11-01'
     AND DATE(my_promos.date) <= '2014-01-22'
     GROUP BY my_promos.event_id) A
ON A.event_id = events.id

我想在codeignitier查询结构

中使用上述内容

1 个答案:

答案 0 :(得分:4)

就是在以下方式中做到这一点

$this->db->join('(SELECT my_promos.event_id, SUM(tickets_sold.quantity) AS my_sold_tickets,
                 (IFNULL(SUM(tickets_sold.price),0)*.10) AS earnings, IFNULL(SUM(tickets_sold.price),0) AS sales
                  FROM my_promos
                  JOIN tickets_sold ON tickets_sold.code = my_promos.link_code
                  WHERE my_promos.user_id = '532' AND DATE(my_promos.date) >= '2013-11-01'
                  AND DATE(my_promos.date) <= '2014-01-23'
                  GROUP BY my_promos.event_id) A','A.event_id = events.id', 'left');

简单..! :)