简体   繁体   中英

how to get the distinct data from a table and then join other table and take sum of 2 columns

I have two tables one table consisting of my order details and other table having the product details. I want to get the distinct products ordered and their id also sum of same products ordered and price

$query = $this->db->query('SELECT 
distinct("productid,picture"),SUM(quantity) as `quantity`,SUM(price) as 
`amount` FROM `order_details` LEFT OUTER JOIN `products` ON 
`products.serial`=`order_details.productid` where `order_details.user_id` = 
`$data[results]`');
 return $query->result();

Above is the query i used and if an user ordered a product multiple times and multiple days means i want to get the distinct of product and its id from the table order_details as well as i need the sum of same orders as quantity and sum of price of the same product and join it with another table named products to get the product name based on productid stored on order_details table

Tables details:

My order_details table consists of (user_id,productid,quantity,price ). Under the productid 3,3,2 are the productids, and under the quantity 10,10,11 etc, and under the price: 64,64,396 etc.

The table products table have (serial,name,price,picture) . What i want is to show products with id 3 and 2 then take sum of quantity of each product and also take sum of price of each product. Actually this is for an ecomerce project. the user logged in to view his orders.

Try next query, first you have to inner join products with order_details, this way you can discard all products that was never ordered. Second, you group by the products common attributes, and then use aggregation methods over those groups.

$query = $this->db->query(
   'SELECT
        p.serial,
        p.picture,
        p.name,
        SUM(o.quantity) AS total_ordered_quantity,
        SUM(o.price) AS total_amount
    FROM
        products AS p
    INNER JOIN
        order_details AS o ON o.productid = p.serial
    WHERE
        o.user_id = $the_user_id
    GROUP BY
        p.serial, p.picture, p.name'
);

return $query->result();

You can check a working example of the query on next link:

http://sqlfiddle.com/#!9/c2a1b0/1

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