PHP中带IF条件的Mysql选择查询

PHP中带IF条件的Mysql选择查询,php,mysql,codeigniter,Php,Mysql,Codeigniter,我正在编写一个mysql查询,以根据id查找两个字段的总和。我已经尝试在select查询中使用IF条件编写查询。我的问题是: `SELECT (IF(`tax_rate_id`=2,SUM(`net_unit_price`*`quantity`),0)) AS sale5 (IF(`tax_rate_id`=3,SUM(`net_unit_price`*`quantity`),0)) AS sale145 FROM sma_sale_items where sale

我正在编写一个mysql查询,以根据id查找两个字段的总和。我已经尝试在select查询中使用IF条件编写查询。我的问题是:

`SELECT (IF(`tax_rate_id`=2,SUM(`net_unit_price`*`quantity`),0)) AS sale5

    (IF(`tax_rate_id`=3,SUM(`net_unit_price`*`quantity`),0)) AS sale145

    FROM sma_sale_items

    where sale_id=4221`

我不知道我的问题是否正确。。如果不可能,是否有其他方法来实现这一点?我还想在codeigniter中执行相同的查询。谁能帮我一下吗?

你可以用条件和来表示和

select
sum( case when tax_rate_id = 2 then net_unit_price*quantity else 0 end) as sale5,
sum( case when tax_rate_id = 3 then net_unit_price*quantity else 0 end) as sale145
from sma_sale_items
where sale_id=4221
MySQL查询

SELECT IF(`tax_rate_id`=2,
          SUM(`net_unit_price`*`quantity`),
          0) AS sale5,
       IF(`tax_rate_id`=3,
          SUM(`net_unit_price`*`quantity`),
          0) AS sale145 
FROM sma_sale_items 
WHERE sale_id=4221
您可以在codeigniter中这样使用

 $this->db->select('IF(`tax_rate_id`=2,SUM(`net_unit_price`*`quantity`),0) AS sale5', FALSE);
    $this->db->select('IF(`tax_rate_id`=3,SUM(`net_unit_price`*`quantity`),0) AS sale145', FALSE);
    $this->db->from('sma_sale_items');
    $this->db->where(array('sale_id'=>4221));
    $result = $this->db->get();

    echo $this->db->last_query();

你的查询在mysql中运行得很好。但是你能告诉我当用codeigniter编写时它是如何产生的吗?我不是
codeigniter
方面的专家,但是你仍然可以使用
$query=$this->db->query(“你的查询”)在CI中运行原始查询而不是查询生成器。$query=$this->db->query(“从销售id=4221的sma\U销售项目中选择sum(税率为2的情况下,净单价为0结尾)作为sale5,sum(税率为3的情况下,净单价为0结尾)作为sale145”);我试着像你在codeigniter中的查询一样。。但它不会给出任何结果。请检查上次执行的查询`echo$this->db->last_query()`