Codeigniter模型:汇总,加入,分组在多个表中

时间:2017-07-18 08:43:12

标签: php mysql codeigniter frameworks

我正在使用Codeigniter,我希望通过id_user汇总总数量和分组:

表1:user_table

user_ID |  name    |
------  | ------   |
   1    |  John    |
   2    |  Frank   |
   3    |  Jesse   |
   4    |  Patrick |
   5    |  Lucy    |

表2:sales_table

sales_ID | user_ID | qty |
 ------  | ------  | ----- |
    1    | 1       |  23   |
    2    | 1       |  11   |
    3    | 2       |  10   |
    4    | 4       |  8    |
    5    | 3       |  14   |
    6    | 5       |  15   |
    7    | 3       |  7    |

结果:

   No    |  Name   | total qty |
 ------  | ------  | --------- |
    1    |  John   |    34     |
    2    |  Frank  |    10     |
    4    |  Patrick|    8      |
    5    |  Jesse  |    21     |
    6    |  Lucy   |    15     |

如何在我的模型和控制器中使用CodeIgniter执行此结果? 有人请帮帮我吗?

3 个答案:

答案 0 :(得分:0)

答案如下(但是你的意思是提供你所尝试的而不是期望人们为你做的事情:o))

SELECT ut.`name`,SUM(st.qty) as `total_qty`
FROM user_table ut
LEFT JOIN sales_table st USING (user_ID)
GROUP BY ut.user_ID

以下是Codeigniter中的内容:

$db = $this->db;

$db->select('ut.name,SUM(st.qty) as total_qty');
$db->join('sales_table st','user_ID','left');
$db->group_by('ut.user_ID');

$data = $db->get('user_table ut')->result_array();

答案 1 :(得分:0)

SELECT name, sum(qty) as total_qty FROM sales_table 
LEFT JOIN user_table ON user_table.user_ID = sales_table.user_ID
GROUP BY sales_table.user_ID

答案 2 :(得分:0)

使用此:

$sql="SELECT ut.user_ID as No, SUM(st.qty) as total_qty , ut.name FROM sales_table st INNER JOIN user_table ut ON ut.user_ID = st.user_ID";
$query  = $this->db->query($sql);
$result = $query->result();
print_r($result);

OR

$this->db->select('ut.user_ID as No, SUM(st.qty) as total_qty , ut.name');
$this->db->from('sales_table st');
$this->db->join('ser_table ut', 'ut.user_ID = st.user_ID');
$query  = $this->db->get();
$result = $query->result();
print_r($result);