I'm making a web application to make customers order items for anything. For that I've made a MySQL database which has the following tables:
customers
orders
order-items
products
In the customers table is all the information about the person such as:
The customer ID, for the primary key and auto increment (id)
The first name (first_name)
The last name (last_name)
The email address (email_adress)
Information about the customer (customer_info)
Example:
In the orders table is all the specific information about it such as:
The order ID, for the primary key and auto increment (id)
Which customer ordered it, linked with id field from the customers table (customer_id)
Order information (order_info)
The location where the order needs to go to (location)
When the order was created (created)
Example:
In the order-items table are all the items which every customer ordered, this is being linked by the order-id from the previous table.
The ID, for primary key and auto increment, not used for any relation (id)
The order ID, used for which product is for which order. This is linked with the id field from the orders table (order_id)
The product ID, this is used for what product they ordered, this is linked with the id field from the products table. (product_id)
The amount of this product they ordered (quantity)
Example:
In the products table is all the information about the products:
The ID, for primary key and auto incrementing, This is linked with the product_id field from the order_items table (id)
The name of the product (name)
The description of the product (description)
The price of the product (price)
Example:
The problem
Bob ordered product_id 2, times 3. Which is the sandwich with beef with the price of 2.50, which we have to multiply by 3 because it has been ordered 3 times. Which is 7.50
Bob also ordered product_id 3, times 5. Which is the sandwich with chicken with the price of 3.00, which we have to multiply by 5 because it has been ordered 5 times. Which comes out on 15.00
Now I need to sum these up. Which is 15.00 + 7.50 = 22.50
The question
How do I get the product_id linked with the actual price of the product_id? which I can then multiply by the quantity.
And then sum up all those values with the same order_id
For the first order we get product 2 (Quantity 3) and product 3 (Quantity 5), which should add 2.503 + 3.005 = 22.50
You asked, "
How do i get the product_id linked with the actual price of the product_id? Which i can then multiply by the quantity... And then sum up all those values with the same order_id."
Like this:
SELECT OI.Order_ID, Sum(OI.Quantity * P.Price) Total_Price
FROM `order-items` OI
INNER JOIN Products P
on OI.Products_Id = P.ID
GROUP BY OI.Order_ID
Expected output for sample data in question:
ORDER_ID Total_price
1 22.50
This is why I asked about sample Output. I'm not sure what columns you were trying to return so I returned just the sum total for each order.
Now what this says
Return a row for each order showing the order ID and the total_price which is the sum of (quantity ordered * price all lines for that order.
This is accomplished by looking at the order-items table (in back tic's because I'm not sure if mySQL like's dashes (-) in names.). Joining these tables based on the product_Id between the ordered items table and the price table. and then group the results by the ordered item allowing the sum to aggregate all the rows for an order times the price of the item on that line of the order together.
You can build an intermediate table that has the totals for each order, then JOIN that with the orders table to get the customerID of that order, which you join with customers to get the customer name
SELECT C.FirstName, C.LastName, Totals.Order_ID, Totals.NetCost
FROM (SELECT OI.order_id, SUM(OI.quantity * P.price) as NetCost
FROM orderitems as OI INNER JOIN products as P ON OI.products_id = P.id
GROUP BY OI.order_id
) as Totals
INNER JOIN orders as O on O.ID = Totals.order_id
INNER JOIN customers as C on C.ID = O.customer_id
And the problem #xQbert is talking about is that if your customer places an order on Monday, you raise your price on Tuesday, and run this report on Wed, the report will show a total different from what the customer saw when he approved the order. A better design would be to store orderprice in orderitem, or at least the ordertotal in orders so subsequent price changes don't affect historic orders. The former is better in case a customer wants a refund on one item.
EDIT: I mean the problem #xQbert mentions in his comment, his answer came in ahead of mine but I missed it on the refresh
EDIT 2: More explanation, as requested by #Bas
It's easiest to think of this query from the inside and work outward, so let me start with getting the prices of items.
I want to link an item in orderitem with it's price, so JOIN orderitem (I give it an alias of OI) to products (I give an alias of P) on the product ID. Product ID is called products_id in OrderItem, but just ID in products.
Once I have that, I can multiply the price from Products by the quantity in OrderItems to get a cost for just that item
Because I want the total of everything for each order, I use a GROUP BY clause on this sub query, with the thing I'm grouping by being order_id. With a GROUP BY, you usually take the field or fields you are grouping by, and some "aggregate" fields where you take the sum, or max, or average, or whatever of them, and it's the sum or whatever for all rows that are in the same group.
So at this point we have defined the query inside the parenthesis. I named that Totals, and it acts just like a real table, but it goes away when your query is over.
The next step is to combine this "totals" table with your orders table so we can look up the customer ID, and then combine it with Customers so we can look up the customer name. I used aliases for Customer and Orders (C and O respectively), but they are not necessary. In fact, this could be rewritten most if not all of the aliases. I think it makes it more readable, but if they confuse you, you could use the following instead, it's the same. I think Totals is necessary, but maybe not even that.
SELECT FirstName, LastName, Totals.Order_ID, Totals.NetCost
FROM (SELECT order_id, SUM(quantity * price) as NetCost
FROM orderitems INNER JOIN products ON products_id = products.id
GROUP BY order_id
) as Totals
INNER JOIN orders on orders.ID = Totals.order_id
INNER JOIN customers on customers.ID = orders.customer_id
Hopefully this is clear, but if not, leave more comments and I'll further explain tonight or tomorrow.
Related
Here are my 3 tables:
Products : (id, product_name)
Purchase Product : (id, product_id, purchase_price, quantity)
Sales Product : (id, product_id, sales_price, quantity, purhase_price)
I want to find the products which are on the purchase list as well as the sales list. If it's not on it the sales list it should return NULL for sales value as well as quantity.
Here same product has different different purchase price so I need to track which purchase product has been sold. But with the group by it's showing the wrong sum.
What could be a possible error of my query?
Here's my query:
$products = DB::table('products')
->join('purchase_products','purchase_products.product_id','products.id')
->leftjoin("sales_products",function($join){
$join
->on("sales_products.purchase_price","purchase_products.purchase_price")
->on("sales_products.product_id","purchase_products.product_id");
})
->select('products.product_name','purchase_products.purchase_price',DB::raw("SUM(purchase_products.quantity) as purchase_quantity"),'sales_products.sales_price',DB::raw("SUM(sales_products.quantity) as sales_quantity"))
->groupby('products.id','purchase_products.purchase_price')
->get();
When you join multiple tables, what is being summed is every combination of the joined tables. So if you have two sales records for a product, the sum of the distinct purchases will be doubled.
I can't tell you how to do it in laravel, but you can remove your sales join and use products.id in (select product_id from sales_products) instead to tell if a product has a sale, or instead of joining sales_products and purchase_products at the same time, join products and sales_products in a subquery that only returns distinct product ids.
Or if you really don't want to change your query structure, you can just change:
SUM(purchase_products.quantity)
to
SUM(purchase_products.quantity) / GREATEST(1, COUNT(sales_products.id))
By the way, I don't see where in your query you are setting sales to null if the product is not on the sales list.
Also, you probably want to group by purchase_products.id instead of purchase_products.purchase_price, in case a product has the same price twice.
I am building a e-commerce website using MySQL. I am stuck with the following.
I have the
**products** table:
id | sku
**stocks** table:
id | product_id |quantity
**orders** table:
id | status | products
I want to know the best way to make SQL query that brings me the products that have 1 or more quantity. To get the quantity of a product: first you get the id from products, then you check the amount in stocks (a product_id can have more than 1 row, I want to add a new row everytime that our store recieve new stock) and subtract the total times that product_id appears on orders table and that row status is 3.
Or if you can suggest me a better way to do this, it would be awesome.
Really appreciate any help here.
Thanks!
This joins products to stocks and gets a list of products where the value in quantity is more or equal one
Just realized you said product id can be stocks more than once therefore i suggest grouping by product id and summing the quantity
SELECT *, SUM(s.quantity) as 'products_total_quantity' FROM products p
INNER JOIN stocks s on s.product_id = p.id
GROUP BY p.id HAVING SUM(s.quantity) >=1
I want to get a list of category items and display the total amount linked to those categories. I have the "amount" field in the "transaction" table and I want to link it to category table.
This is how my tables are:
Category Master
Subcategory Master
Item Master
Transaction
So to get my "Amount" field to category, I would have to pass a certain common column between them. I have CategoryID in SubCategory master, subcatid in item master and similarly itemid in transaction.
Earlier when I grouped the amount using transaction date, the process went smoothly:
SELECT TransactionDate, SUM(Amount) FROM transaction GROUP BY MONTH(TransactionDate)
Now the problem I'm facing with grouping it using categoryname is that all of the amount seems to be =50 whereas it is still different in the database. I know that this is something really silly, but I am comparatively new to programming and not sure how to use logic appropriately.
SELECT categorymaster.CategoryName, transaction.Amount
FROM categorymaster
INNER JOIN subcategorymaster
INNER JOIN itemmaster
INNER JOIN transaction
GROUP BY categorymaster.CategoryName
This answer assumes your primary key in each table is named "ID". You didn't provide that info.
SELECT categorymaster.CategoryName, sum(transaction.Amount)
FROM categorymaster
INNER JOIN subcategorymaster
ON subcagetorymaster.CategoryId = categorymaster.ID
INNER JOIN itemmaster
ON itemmaster.SubCatId = subcategorymaster.ID
INNER JOIN transaction
ON transaction.ItemId = itemmaster.ID
GROUP BY categorymaster.CategoryName
I want to be able to list all items that have been purchased in every order for all orders where an item within that order is a specific item.
Eg: I want to be able to do a search for all orders where tomato ketchup has been ordered and list all the products in these orders.
I want to be able to say, therefore, for all customers that purchased tomato ketchup, what other products accompanied that item.
Its similar to what you would expect to see in any cyber market place where "others also bought..."
The database I am using has a table with products and an order ID. I imagine the simplest way is to write a PHP script to perform 2 queries, one to return all orders containing the item in question and another to list all items for each of the order IDs. But I had hoped there was a "clever" query that could replace that.
My ultimate goal would be to search for all orders where a list of items exist. The idea is to try and whittle down the results to only show those where the specified combination of products has been found.
Assuming:
products(id integer, name varchar(25) and orders (id integer) and order_items (order_id integer, product_id integer)
Use this:
SELECT oi.order_id, p2.name
FROM products p
INNER JOIN order_items oi
ON p.id = oi.product_id
INNER JOIN order_items oi2
ON oi.order_id = oi2.order_id
INNER JOIN products p2
ON oi2.product_id = p2.id
WHERE p.name = 'Carrot'
Fiddle example: http://sqlfiddle.com/#!9/0b9f4/2
I'm making a web application to make customers order items for anything. For that I've made a MySQL database which has the following tables:
customers
orders
orders-items
products
In the customers table is all the information about the person such as:
The customer ID, for the primary key and auto increment (id)
The first name (first_name)
The last name (last_name)
The email address (email_address)
Information about the customer (customer_info)
Example:
In the orders table is all the specific information about it such as:
The order ID, for the primary key and auto increment (id)
Which customer it ordered, linked with id field from the customers table (customer_id)
Order information (order_info)
The location where the order needs to go to (location)
The total price the customer has to pay (total_price)
When the order was created (created)
Example:
In the orders-items table are all the items which every customer ordered, this is being linked by the order-id from the previous table.
The ID, for primary key and auto increment, not used for any relation (id)
The order ID, used for which product is for which order. This is linked with the id field from the orders table (order_id)
The product ID, this is used for what product they ordered, this is linked with the id field from the products table. (product_id)
The amount of this product they ordered (quantity)
Example:
In the products table is all the information about the products:
The ID, for primary key and auto incrementing, This is linked with the product_id field from the order_items table (id)
The name of the product (name)
The description of the product (description)
The price of the product (price)
Example:
Question:
I've got this query:
SELECT `orders-items`.`order_id` , SUM(`orders-items`.`quantity`* `products`.`price`) total
FROM `orders-items`
INNER JOIN `Products` ON `orders-items`.`products_id` = `products`.`id`
And it shows me a list of all the total prices every order_id has to pay.
But how do I make this so that this value of the total_price every order_id has to pay is automatticly inserted into the orders table inside the total_price field at the right order_id when inserting a product into my orders-list table?
Or is it still better to not keep track of the total_prices the customers have to pay?
A couple things to consider.
Having a total_price for itself is redundant. You can learn this total by summing the prices of this order's items at any time. It might be interesting to have it for performance reasons, but is this really necessary for your scenario? It rarely is.
Having a price on each order_item in the other hand would be useful. And the why is because thoses products prices might change in the future and you don't want to lose information of for how much they were sold at the time of that particular sale.
In any case, you can update your total_price using triggers like this:
DELIMITER $$
CREATE TRIGGER order_items_insert AFTER INSERT ON `orders-items` FOR EACH ROW
BEGIN
UPDATE orders o INNER JOIN (SELECT i.order_id id, SUM(i.quantity * p.price) total_price FROM `orders-items` i INNER JOIN products p ON p.id = i.products_id AND i.order_id = new.order_id) t ON t.id = o.id SET o.total_price = t.total_price;
END$$
CREATE TRIGGER order_items_update AFTER UPDATE ON `orders-items` FOR EACH ROW
BEGIN
UPDATE orders o INNER JOIN (SELECT i.order_id id, SUM(i.quantity * p.price) total_price FROM `orders-items` i INNER JOIN products p ON p.id = i.products_id AND i.order_id = new.order_id) t ON t.id = o.id SET o.total_price = t.total_price;
END$$
CREATE TRIGGER order_items_delete AFTER DELETE ON `orders-items` FOR EACH ROW
BEGIN
UPDATE orders o INNER JOIN (SELECT i.order_id id, SUM(i.quantity * p.price) total_price FROM `orders-items` i INNER JOIN products p ON p.id = i.products_id AND i.order_id = old.order_id) t ON t.id = o.id SET o.total_price = t.total_price;
END$$
DELIMITER ;
One Option would be a trigger, which is executed on inserting a new customer.
Alternative you could going for a stored procedure. With this, you only need to call the procedure InsertCustomer, and the database handles the price update for you -> you will not have these dependencies in your Application.
Another way could be, to do 2 querys (insert and update) in a transaction. But for this i recommend Domain Driven Design. You would have a service, which has the method CreateCustomer(Customer $customer), which do a insert query and then the update query. On success it commits the transaction and returns true, if not success, it cancel the transaction and reuturns false. It should be your own convention to only manipulate data with help of the services (which knows the business logic).