带有if条件的CI 3.1.0查询

时间:2016-08-30 07:20:28

标签: mysql sql

SELECT cat.categoryId, cat.categoryName, coupon.* 
FROM `wrh_category` AS `cat`
INNER JOIN `wrh_coupon` AS `coupon` ON `cat`.`categoryId` = `coupon`.`categoryId`
LEFT JOIN `wrh_saved_coupon` AS `savedCoupon` ON `coupon`.`couponId` = `savedCoupon`.`couponId` AND `savedCoupon`.`is_deleted` = 0
WHERE `cat`.`categoryId` = 2
AND `cat`.`is_deleted` =0
AND `coupon`.`is_deleted` =0
AND `coupon`.`startDate` <= '2016-08-30 07:14:53'
AND `coupon`.`expiryDate` > '2016-08-30 07:14:53'
 LIMIT 2;

我想再显示一个名为'isSaved'的虚拟列, 根据以下条件,值应为“1”或“0”

if (`coupon`.`couponId` == `savedCoupon`.`couponId`)
    return 1;
else
    return 0;

2 个答案:

答案 0 :(得分:1)

尝试这个如果编纂:

IF(`coupon`.`couponId` == `savedCoupon`.`couponId`,1,0) as isSaved

在选择为:

SELECT cat.categoryId, cat.categoryName, coupon.*, IF(`coupon`.`couponId` == `savedCoupon`.`couponId`,1,0) as isSaved
FROM `wrh_category` AS `cat`
INNER JOIN `wrh_coupon` AS `coupon` ON `cat`.`categoryId` = `coupon`.`categoryId`
LEFT JOIN `wrh_saved_coupon` AS `savedCoupon` ON `coupon`.`couponId` = `savedCoupon`.`couponId` AND `savedCoupon`.`is_deleted` = 0
WHERE `cat`.`categoryId` = 2
AND `cat`.`is_deleted` =0
AND `coupon`.`is_deleted` =0
AND `coupon`.`startDate` <= '2016-08-30 07:14:53'
AND `coupon`.`expiryDate` > '2016-08-30 07:14:53'
 LIMIT 2;

您可以在CI中使用它:

$query = $this->db->query("YOUR QUERY");

$query = $this->db->query("SELECT cat.categoryId, cat.categoryName, coupon.*, IF(`coupon`.`couponId` == `savedCoupon`.`couponId`,1,0) as isSaved
    FROM `wrh_category` AS `cat`
    INNER JOIN `wrh_coupon` AS `coupon` ON `cat`.`categoryId` = `coupon`.`categoryId`
    LEFT JOIN `wrh_saved_coupon` AS `savedCoupon` ON `coupon`.`couponId` = `savedCoupon`.`couponId` AND `savedCoupon`.`is_deleted` = 0
    WHERE `cat`.`categoryId` = 2
    AND `cat`.`is_deleted` =0
    AND `coupon`.`is_deleted` =0
    AND `coupon`.`startDate` <= '2016-08-30 07:14:53'
    AND `coupon`.`expiryDate` > '2016-08-30 07:14:53'
     LIMIT 2")->result();

答案 1 :(得分:0)

$this->db->select("cat.categoryId, cat.categoryName, coupon.*, IF(coupon.couponId == savedCoupon.couponId,1,0) as isSaved", FALSE); <br/>
$this->db->from("wrh_category AS cat");<br/>
$this->db->join("wrh_coupon AS coupon", "cat.categoryId = coupon.categoryId", 'inner');<br/>
$this->db->join("wrh_saved_coupon AS savedCoupon", "coupon.couponId = savedCoupon.couponId AND savedCoupon.is_deleted = 0", 'left');<br/>
$this->db->where("cat.categoryId", $catgoryId);<br/>
$this->db->where("cat.is_deleted", 0);<br/>
$this->db->where("coupon.is_deleted", 0);<br/>
$dt = new DateTime('now');<br/>
$dt = $dt->format('Y-m-d H:i:s');<br/>
$this->db->where('coupon.startDate <=', $dt);<br/>
$this->db->where('coupon.expiryDate >', $dt);<br/>
$this->db->limit($limit, $index);<br/>
$query = $this->db->get();