簡體   English   中英

Codeigniter模型:摘要,聯接,在多個表中分組

[英]Codeigniter Model: summary, join, group by in multiple table

我正在使用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獲得此結果? 有人請幫我嗎?

答案如下(但您並不是要提供自己嘗試過的東西,而不是期望人們為您提供幫助: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();
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

用這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM