简体   繁体   中英

Codeigniter Model: summary, join, group by in multiple table

I'm using Codeigniter, what I want to summary total qty and group by id_user:

TABLE 1: user_table

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

TABLE 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    |

Result:

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

How can I do this result with CodeIgniter in my model and controller? Somebody please help me?

The answer is as follows (but you are mean't to provide what you have tried rather than expect people to do it for you :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

Here is how this would look in 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

Use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM