【问题标题】:how to get the distinct data from a table and then join other table and take sum of 2 columns如何从表中获取不同的数据,然后加入其他表并取 2 列的总和
【发布时间】:2019-03-25 06:15:40
【问题描述】:

我有两张表,一张包含我的订单详细信息,另一张包含产品详细信息。我想订购不同的产品,它们的 id 也是订购的相同产品和价格的总和

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

上面是我使用的查询,如果用户多次和多天订购产品意味着我想从表 order_details 中获取产品的不同及其 id,并且我需要相同订单的总和作为数量和将同一产品的价格总和与另一个名为 products 的表连接起来,根据 order_details 表中存储的 productid 获取产品名称

表格详情:

我的 order_details 表由 (user_id,productid,quantity,price 组成。 productid 3,3,2 下是productids,数量下是10,10,11 等,价格下是:64,64,396 等。

products表有(serial,name,price,picture)。 我想要的是显示 id 为 3 和 2 的产品,然后计算每个产品的数量总和,并计算每个产品的价格总和。实际上这是一个电子商务项目。用户登录查看他的订单。

【问题讨论】:

    标签: php mysql codeigniter-3


    【解决方案1】:

    尝试下一个查询,首先你必须inner join带有order_details的产品,这样你就可以丢弃所有从未订购过的产品。其次,您产品共同属性分组,然后对这些组使用聚合方法。

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

    您可以在下一个链接上查看查询的工作示例:

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

    【讨论】:

    • 让我检查一下好吗
    • 但似乎是这样的错误:您的 SQL 语法有错误;查看与您的 MariaDB 服务器版本相对应的手册,了解在 'WHERE o.user_id = $data[results]' 附近使用的正确语法
    • 这是输出查询: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 GROUP BY p.serial, p.picture, p.name WHERE o.user_id = $data[results]
    • 您能否添加填充$data 变量的代码部分。所以我们可以看到为什么这不起作用...无论如何,为了测试查询,只需将 $data[results] 替换为 user_id,例如 1、2 或您拥有的任何有效 id。
    • 现在查询是: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 @ 987654344@ AS o ON o.productid = p.serial GROUP BY p.serial, p.picture, p.name WHERE o.user_id = 1
    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 2017-04-07
    • 2020-08-06
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多