![](/img/trans.png)
[英]How to join two tables and then display the sum value of each data of a table gathering from the other table
[英]how to get the distinct data from a table and then join other table and take sum of 2 columns
我有兩個表,一個表包含我的訂單詳細信息,另一個表包含產品詳細信息。 我想訂購不同的產品,它們的編號也等於訂購的相同產品和價格的總和
$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的區別,以及我需要與數量和價格總和相同的訂單總和相同商品的商品,並將其與另一個名為商品的表結合起來,以基於存儲在order_details表中的商品ID獲得商品名稱
表格詳情:
我的order_details表由(user_id,productid,quantity,price
)組成。 在產品編號3,3,2下是產品編號,在數量10,10,11等下,並且在價格下:64,64,396等。
表產品表有(serial,name,price,picture)
。 我想要的是顯示ID為3和2的產品,然后取每個產品的數量之和,還取每個產品的價格之和。 實際上這是一個生態商業項目。 用戶登錄查看其訂單。
嘗試下一個查詢,首先您必須使用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();
您可以在下一個鏈接上查看查詢的工作示例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.