2017-07-18 26 views
0

我使用笨,我想大概的總數量和group by 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執行此結果? 有人請幫幫我嗎?

+1

你到目前爲止試過的是什麼? –

+0

這個問題可能屬於sql系列,而不是php。 – sitilge

回答

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); 

$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); 
0

答案如下(但你mean't提供你已經嘗試,而不是指望別人爲你做什麼: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 

這裏是如何做到這一點看在笨:

$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(); 
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