简体   繁体   English

如何从一个表中获取不同的数据,然后联接另一个表并取2列之和

[英]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 上面是我使用的查询,如果用户多次订购产品,这意味着我想从表order_details中获得产品及其ID的区别,以及我需要与数量和价格总和相同的订单总和相同商品的商品,并将其与另一个名为商品的表结合起来,以基于存储在order_details表中的商品ID获得商品名称

Tables details: 表格详情:

My order_details table consists of (user_id,productid,quantity,price ). 我的order_details表由(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. 在产品编号3,3,2下是产品编号,在数量10,10,11等下,并且在价格下:64,64,396等。

The table products table have (serial,name,price,picture) . 产品表有(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. 我想要的是显示ID为3和2的产品,然后取每个产品的数量之和,还取每个产品的价格之和。 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. 尝试下一个查询,首先您必须使用order_details 内部连接产品,这样您就可以丢弃所有从未订购的产品。 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 http://sqlfiddle.com/#!9/c2a1b0/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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