Need help on SQL Query with 4 tables - mysql

Currently I have the following 4 tables: customer, customer_orders_product, customer_order and customer
What I am trying to do is to run a query that could show the following columns:
order_id, product_name, quantity and order total (which is quantity *
product_price)
But I am not sure if there is any query that is capable to do so, any help on this?
Furthermore, is there any query with JOIN syntax that I could run with those 4 tables?

You just join each pair of tables according to the fields that reference each other:
SELECT co.order_id,
p.product_name,
cop.quantity,
cop.quantity * p.product_price AS total
FROM customer_order co
JOIN customer_order_product cop ON co.order_id = cop.order_id
JOIN product p ON cop.product_id = p.product_id
Incidentally, you don't need all four tables for this query - the customer details are irrelevant for your question.

Related

MySQL inner join query select from same table multiple times

I believe I have formed this question title correctly because I wasn't sure how to form it. As an example, I have summarized my query below.
I have an order table which saves order details like customer id, address and product ids and quantity ordered for each order in a row. So multiple inventory/product ids are saved in a single row.
so my query looks like: this is a summarized query for an easier explanation I have omitted various other fields.
SELECT customer.name,customer.address,tbl_order.order_date,tbl_order.product1_id,tbl_order.product2_id,inventory.product1_name,inventory.product2_name
FROM tbl_order
INNER JOIN customer ON tbl_order.customer_id = customer.id
INNER JOIN inventory on tbl_order.product1_id = inventory.id
INNER JOIN inventory on tbl_order.product2_id = inventory.id
where YEAR(tbl_order.order_date)='$year'
So my question is how to get the inventory details from the inventory table based on each product id from tbl_order. I am running a while loop to show all data for a year
while($row=mysqli_fetch_assoc($sql1))
I can divide this query into 2 and run the inventory query individually but then how to combine the while loop, as sometimes there could also be empty query when some products are not in order table (depending on order to order, not all products are ordered) so this doesn't work
while($row=mysqli_fetch_assoc($sql1)) and ($row1=mysqli_fetch_assoc($inv1)) and ($row2=mysqli_fetch_assoc($inv2))
and so one for 10 products
First, of all you have bad DB design and I kindly advice to normalize your DB.
Second, if you can not re-design the DB you can use multiple joins with aliases like:
SELECT
customer.name, customer.address, tbl_order.order_date,
tbl_order.product1_id, inv1.product1_name,
tbl_order.product2_id, inv2.product2_name
FROM tbl_order
INNER JOIN customer ON tbl_order.customer_id = customer.id
INNER JOIN inventory AS inv1 ON tbl_order.product1_id = inv1.id
INNER JOIN inventory AS inv2 ON tbl_order.product2_id = inv2.id
WHERE YEAR(tbl_order.order_date)='$year'

Possibly advanced SQL query UNION of 3 Tables

Goal. To make a query that displays Product Name(Products), Product Type(ProductTypes), and total number of sales of each product(Sales)
Here are my tables:
I am having real difficulty figuring out how I am meant to do this. I am trying to do a UNION and a few other things but cannot get it to work.
I can get the total number of sales by using this SELECT ProductID, count(*) as NumSales from Sales group by ProductID but really struggling to do the rest and format it correctly. Any help would be appreciated.
EDIT:
Select Products.ProductName, ProductTypes.ProductType
From Products
INNER JOIN ProductTypes ON Products.ProductTypeID=ProductTypes.ProductTypeID
I have this to display this right now, just need to join the sales count somehow.
try:
select prod.ProductName, ptyp.ProductType, count(SaleID) count_sale
from Products prod
join ProductTypes ptyp on ( ptyp.ProductTypeID= prod.ProductTypeID)
join Sales sal on ( sal.ProductID = prod.ProductID)
group by prod.ProductName, ptyp.ProductType

SQL average and Join

I'm trying to merge these two statements into one query to get the a list of product names(or ids) against the average of their TTFF data, and I'm stuck.
select AVG(TTFF) from TTFFdata group by product_id
select product.product_name, count(*) from product join TTFFdata on product.product_id = TTFFdata.product_id
I've looked into using a temporary table (CREATE TEMPORARY TABLE IF NOT EXISTS averages AS (select AVG(TTFF) from TTFFdata group by product_id)) but couldn't get that to work with a join.
Anyone able to help me please?
You need to understand the components. Your second query is missing a group by. This would seem to be what you want:
select p.product_name, count(t.product_id), avg(t.TTFF)
from product p left join
TTFFdata t
on p.product_id = t.product_id
group by p.product_name
It is better to do group by on product_id, product_name for two reasons. One is, you can select product id along with product name. Second reason is, If the product name is not unique then it may give wrong results(this may be a rare scenario like product name is same but it differs based on other columns like version or model). The below is the final query.
select Product.product_id,
product_name,
AVG(TTFF) as Avg_TTFF
from Product
inner join
TTFFdata
on Product.product_id = TTFFdata.product_id
group by Product.product_id,Product.product_name
TTFFdata:
product:
Output:

Mysql - How to make this work?

I have a mysql table Products.
It contains the Columns "id,product_name,product_seller,price"
I am trying to create a PHP script to Insert/Update data in the table Products using the seller name (product_seller).
The issue
I don't know what mysql query to use in order to get: A list with All the products NO matter if the seller has it or not and if the seller has the products to give me the details (id,product_name,product_seller,price).
EXAMPLE of what i want to get:
1 - apples - seller A - 12
2 - banana - -
3 - oil - -
4 - dvd - seller A - 25
The product_name must be DISTINCT
Thanks in advance!
* Query must be something like "SELECT DISTINCT product_name FROM Products and let me know where Seller A has the product, at what price, what id what product WHERE seller_name = 'seller A'...yet, show me all products, n matter if seller has it"
Seems to be a straight forward subquery to get a unique list of products then an outer join to get the seller info.
SELECT A.ID, A.Product_name, B.product_Seller, B.Price
FROM (SELECT DISTINCT ID, Product_Name FROM products) A
LEFT JOIN Products B
on A.ID = B.ID
and B.product_Seller = 'seller A'
The LEFT JOIN will ensure you return all the products and only seller information related to the items for 'SELLER A'
SQL generally operates best on data SETS. So I first generate a set of unique IDs and products and then LEFT JOIN this to the sellers product data you desire. The left join ensures we keep all the items. The filtering of the seller MUST be on the JOIN itself and not in the where clause. Otherwise the left join in essence becomes an inner as the NULLS generated from the outer join are removed.
SELECT A.ID, A.Product_name, B.product_Seller, B.Price
FROM (SELECT DISTINCT ID, Product_Name FROM products) A
LEFT JOIN Products B
on A.ID = B.ID
WHERE B.product_Seller = 'seller A'
Wouldn't get the desired result. This is because the where clause is applied after the join so the items that are not associated to the seller would be excluded. Since you want those records, you must use a left join and apply the limit on the JOIN so the items not associated to the seller are returned.
When I initially started with SQL I had trouble with this type of logic. It wasn't until I considered data in terms of "SETS" and how those sets related, that how to solve these questions became easier.
try to use the
SELECT * FROM Products_Table ;
this will obtain all the table values

MYSQL Count group by rows ignoring effect of JOIN and SUM fields on Joined tables

I have 3 tables:
Orders
- id
- customer_id
Details
- id
- order_id
- product_id
- ordered_qty
Parcels
- id
- detail_id
- batch_code
- picked_qty
Orders have multiple Details rows, a detail row per product.
A detail row has multiple parcels, as 10'000 ordered qty may come from 6 different batches, so goods from batches are packed and shipped separately. The picked quantity put in each parcel for a detail row should then be the same as the ordered_qty.
... hope that makes sense.
Im struggling to write a query to provide summary information of all of this.
I need to Group By customer_id to provide a row of data per customer.
That row should contain
Their total number of orders
Their total ordered_qty of goods across all orders
Their total picked_qty of goods across all orders
I can get the first one with:
SELECT customer_id, COUNT(*) as number_of_orders
FROM Orders
GROUP BY Orders.customer_id
But when I LEFT JOIN the other two tables and add the
SELECT ..... SUM(Details.ordered_qty) AS total_qty_ordered,
SUM(Parcels.picked_qty) AS total_qty_picked
.. then I get results that dont seem to add up for the quantities, and the COUNT(*) seems to include the additional lines from the JOIN which obviously then isn't giving me the number of Orders anymore.
Not sure what to try next.
===== EDIT =======
Here's the query I tried:
SELECT
customer_id,
COUNT(*) as number_of_orders,
SUM(Details.ordered_qty) AS total_qty_ordered,
SUM(Parcels.picked_qty) AS total_qty_picked
FROM Orders
LEFT JOIN Details ON Details.order_id=Order.id
LEFT JOIN Parcels ON Parcels.detail_id=Detail.id
GROUP BY Orders.customer_id
try COUNT(distinct Orders.order_id) as number_of_orders,
as in
SELECT
customer_id,
COUNT(distinct Orders.order_id) as number_of_orders,
SUM(Details.ordered_qty) AS total_qty_ordered,
(select SUM(Parcels.picked_qty)
FROM Parcels WHERE Parcels.detail_id=Detail.id ) AS total_qty_picked
FROM Orders
LEFT JOIN Details ON Details.order_id=Order.id
GROUP BY Orders.customer_id
EDIT: added an other select with subselect
Is there any particular reason you feel the need to combine all these in one query? Simplify by breaking it up in to separate queries, and if you want a single call to get the results, put the queries in a stored procedure, using temp tables.