SQL QUERY Multiple Tables Newby - mysql

I am new to SQL and have the following task I'm trying to complete:
I need to create a query that will return a set of results based on a set of dates. Here are my TABLES/columns:
Order Line
order_id,
line_no,
qty_shipped,
total_shipped_qty,
part_id,
part_description,
desired_ship_date,
ship_date,
customer_id
Shipper
packlist,
order_id
Customer
name,
customer_id
Customer Order
PO,
order_id
I need my output to look like this:
packlist,
order_id,
line_no,
total_shipped_qty,
part_id,
part_description,
name,
po,
desired_ship_date,
ship_date,
So far I have come up with a query below that gets me all the column data I need from the Order Line Table based on a set of dates. I'm having trouble joining the other tables together to get the rest of the columns I need in my output. Specifically packlist, po, and name from their tables. I need to run this query first:
SELECT ORDER_ID,
LINE_NO,
TOTAL_SHIPPED_QTY,
PART_DESCRIPTION,
DESIRED_SHIP_DATE,
SHIP_DATE,
TOTAL_SHIPPED_QTY
FROM ORDER_LINE
WHERE [SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX'
Based on the results above I need to pull in the rest of the data from the other tables. Any help is greatly appreciated. Thank you

SELECT s.packlist, o.Order_ID,
o.total_shipped_qty,o.Part_ID, o.Part_Description, co.PO,
c.Name, o.Desired_Ship_Date, o.Ship_Date
from OrderLine o
inner join Customers c on c.Customer_ID = o.Customer_ID
inner join Shipper s on s.Order_ID = o.Order_ID
inner join CustomerOrders co on co.Order_ID = o.Order_ID
WHERE o.[SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX'
I don't think you need to join on CustomerOrders at this point.

Just a INNER JOIN between all the tables is what you need
SELECT S.PACKLIST,
O.ORDER_ID,
O.TOTAL_SHIPPED_QTY,
O.PART_ID,
O.PART_DESCRIPTION,
C.NAME,
CO.PO,
O.DESIRED_SHIP_DATE,
O.SHIP_DATE
FROM ORDERLINE O
JOIN CUSTOMERS C
ON C.CUSTOMER_ID = O.CUSTOMER_ID
JOIN SHIPPER S
ON S.ORDER_ID = O.ORDER_ID
JOIN CUSTOMERORDER CO
ON CO.ORDER_ID = O.ORDER_ID
WHERE O.[SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX'

Related

Why SQL Displays Two Rows Instead of One

Here is the Query
SELECT o.OrderID, o.CNIC,
(SELECT FullName FROM Customer WHERE CNIC=o.CNIC) Customer,
o.Date
FROM orders o
JOIN ordersproduct op ON op.OrderID=o.OrderID
WHERE o.OrderID=1;
Here is the result
1 - 15604-5566123-2 - Shaiz Mehran - 2020-09-30
1 - 15604-5566123-2 - Shaiz Mehran - 2020-09-30
If the purpose is to only show customers who has an order, but no details of the orderproduct itself you could use the following :
SELECT DISTINCT o.OrderID, o.CNIC,
(SELECT FullName FROM Customer WHERE CNIC=o.CNIC) Customer,
o.Date
FROM orders o
WHERE o.OrderID=1;
OR
SELECT DISTINCT o.OrderID, o.CNIC,
c.Customer, o.Date
FROM orders o
INNER JOIN Customer c ON c.CNIC = o.CNIC
WHERE o.OrderID=1;
If this is only the start and you will show the product which the customer ordered it will show two rows as the customer has two products (orderproducts). This will return two rows with different orderproducts
SELECT DISTINCT o.OrderID, o.CNIC,
c.Customer, o.Date op.ColumnTosShow
FROM orders o
INNER JOIN Customer c ON c.CNIC = o.CNIC
INNER JOIN ordersproduct op ON op.OrderID=o.OrderID
WHERE o.OrderID=1;
SELECT Distinct Orders.OrderID, Orders.CNIC, Customer.FullName
FROM (Orders LEFT JOIN Customer ON Orders.CNIC = Customer.CNIC)
LEFT JOIN OrdersProduct ON Orders.OrderID = OrdersProduct.OrderID;
The reason you are getting multiple rows is because an order can have multiple products . . . and you are getting one row per product.
The join to the product table seems quite unnecessary, so just use:
SELECT o.OrderID, o.CNIC,
(SELECT FullName FROM Customer WHERE CNIC=o.CNIC) as Customer,
o.Date
FROM orders o
WHERE o.OrderID = 1;
I am guessing you have a reasonable data model so there are not multiple rows in orders for a given id. SELECT DISTINCT is not necessary.
I should add that JOIN is very reasonable for this query, but like this:
SELECT o.OrderID, o.CNIC, c.FullName as Customer,
o.Date
FROM orders o LEFT JOIN
customer c
ON o.CNIC = c.CNIC
WHERE o.OrderID = 1;

MySQL: Ranking from multiple tables, sub queries?

This is a MySQL question. I have three tables with the following columns:
transactions (table): transact_id, customer_id, transact_amt, product_id,
products (table): product_id, product_cost, product_name, product_category
customers (table): customer_id, joined_at, last_login_at, state, name, email
I'd like a query that finds out the most popular item in every state and the state. One of the tricky parts is that some product_name have multiple product_id. Therefore I though joining the three tables that generate an output with two columns: state and product_name. Until here that worked fine doing this:
SELECT p.product_name, c.state
FROM products p
INNER JOIN transactions t
ON p.product_id = t.product_id
INNER JOIN customers c
ON c.customer_id = t.customer_id
This selects all the products, and the states from where the customer is. The problem is that I can't find the way to rank the mos popular product per state. I tried different group by, order by and using subqueries without success. I suspect I need to do subqueries, but I can't find the way to resolve it. The expected outcome should look like this:
most_popular_product | state
Bamboo | WA
Walnut | MO
Any help will be greatly appreciated.
Thank you!
You need a subquery that gets the count of transactions for each product in each state.
SELECT p.product_name, c.state, COUNT(*) AS count
FROM products p
INNER JOIN transactions t
ON p.product_id = t.product_id
INNER JOIN customers c
ON c.customer_id = t.customer_id
GROUP BY p.product_name, c.state
Then write another query that has this as a subquery, and gets the highest count for each state.
SELECT state, MAX(count) AS maxcount
FROM (
SELECT p.product_name, c.state, COUNT(*) AS count
FROM products p
INNER JOIN transactions t
ON p.product_id = t.product_id
INNER JOIN customers c
ON c.customer_id = t.customer_id
GROUP BY p.product_name, c.state
) AS t
GROUP BY state
Finally, join them together:
SELECT t1.product_name AS most_popular_product, t1.state
FROM (
SELECT p.product_name, c.state, COUNT(*) AS count
FROM products p
INNER JOIN transactions t
ON p.product_id = t.product_id
INNER JOIN customers c
ON c.customer_id = t.customer_id
GROUP BY p.product_name, c.state
) AS t1
JOIN (
SELECT state, MAX(count) AS maxcount
FROM (
SELECT p.product_name, c.state, COUNT(*) AS count
FROM products p
INNER JOIN transactions t
ON p.product_id = t.product_id
INNER JOIN customers c
ON c.customer_id = t.customer_id
GROUP BY p.product_name, c.state
) AS t
GROUP BY state
) AS t2 ON t1.state = t2.state AND t1.count = t2.maxcount
This is basically the same pattern as SQL select only rows with max value on a column, just using the first grouped query as the table you're trying to group.

what is the solution of this query?

I am new to database field. I am currently learning mysql using Murach's Mysql. I came across following problem in the book but I am not able to figure out the correct query for solving it.
Write a SELECT statement that
joins the
Customers, Orders, Order_Items, and
Products tables. This statement should return these columns:
last_name,
first_name,
order_date, product_na
me, item_price, discount_amount,
and
quantity
.
Use aliases for the tables.
Sort the final result set by
last
_name,
order
_date, and
product_name
.
By far I have this query:
select last_name , first_name , order_date , product_name , tem_price,
discount_amount, quantity
from customers , orders , order_items product
order by last_name , order_date , product_name
You can use inner join for these 4 tables Customers , Orders, Order_items , Products but make sure there is a match between the columns in these 3 tables.
Example of the sql query based on the given information. (Assume CustomerID is a match between the columns)
Select A.last_name,A.first_name,B.order_date,B.product_name,C.item_price,C.discount_amount,D.quantity
from TB_Customers A inner join TB_Orders B on A.CustomerID = B.CustomerID
inner join TB_Order_Items C on B.CustomerID = C.CustomerID on
inner join TB_Products D on C.CustomerID = D.CustomerID Where D.CustomerID ='TEST111'
Using ANSI standard join syntax:
SELECT c.last_name, c.first_name, o.order_date, p.product_name,
p.item_price, p.discount_amount, p.quantity
FROM Customers AS c
INNER JOIN Orders AS o ON c.order_id = o.order_id
INNER JOIN Order_Items AS i ON o.order_id = i.order_id
INNER JOIN Products AS p ON i.product_id = p.product_id
ORDER BY c.last _name, o.order _date, p.product_name
Well, we are going to analize the query. Since you didn't specify the database structure, I'm going to do an aproaching.
"SELECT statement that joins the Customers, Orders, Order_Items, and Products tables."
This is refered to the tables, this is in the FROM clause. You have to join them with WHERE clause.
SELECT *
FROM Customers, Orders, Order_Items, Products
WHERE Customers.order_id = Orders.order_id
AND Order_Items.order_id = Orders.order_id
AND Products.product_id = Order_Items.product_id
"This statement should return these columns: last_name, first_name, order_date, product_na me, item_price, discount_amount, and quantity "
This part is refered to the SELECT clause.
SELECT last_name, first_name, order_date, product_name,
item_price, discount_amount, quantity
FROM Customers, Orders, Order_Items, Products
WHERE Customers.order_id = Orders.order_id
AND Order_Items.order_id = Orders.order_id
AND Products.product_id = Order_Items.product_id
"Use aliases for the tables"
This part involves the whole query and means that have to rename the tables (virtually and only form this query) and in every reference you have to use the new name.
SELECT c.last_name, c.first_name, o.order_date, p.product_name,
p.item_price, p.discount_amount, p.quantity
FROM Customers AS c, Orders AS o, Order_Items AS i, Products AS p
WHERE c.order_id = o.order_id
AND i.order_id = o.order_id
AND p.product_id = i.product_id
"Sort the final result set by last _name, order _date, and product_name."
This part refered to th ORDER BY clause. You have to keep in mind the aliases
SELECT c.last_name, c.first_name, o.order_date, p.product_name,
p.item_price, p.discount_amount, p.quantity
FROM Customers AS c, Orders AS o, Order_Items AS i, Products AS p
WHERE c.order_id = o.order_id
AND i.order_id = o.order_id
AND p.product_id = i.product_id
ORDER BY c.last _name, o.order _date, p.product_name

SQL Querying multiple tables using JOIN - Northwind

//Personal understanding, not a hw assignment
So in the sample db northwind from MS there are the tables: orders o, [order details] od, customers c
o has orderID, customerID (inc. duplicates)
od has orderID (inc. duplicates), unitprice, quantity, discount
c has customerID, companyName
roughly speaking,
I want to join on
o.customerID = c.customerID; selecting companyName ///
join on o.orderID = od.orderID; selecting unitprice, quantity, discount
my end goal is to
sum(q (up - d)) AS 'Order Total' group by od.orderID then
sum(Order Total) group by companyName(?)
My main issue is not know how/what to join properly though.
Thanks in advance
Check out your scenario on SQL Fiddle
SELECT comp.`company_name` AS 'company',COUNT(DISTINCT o.id_sales_order) AS 'total_orders',SUM(`unit_price`) AS 'grand_total'
FROM sales_order AS o
LEFT JOIN sales_order_item AS od ON od.fk_sales_order = o.id_sales_order
LEFT JOIN customer AS c ON c.id_customer = o.fk_customer
LEFT JOIN company AS comp ON comp.id_company = c.fk_company_id
GROUP BY comp.`company_name`
hope this what you are looking for
Assuming that you create the correct Select statement as you required, the join part should be something like:
From Orders o join Order_Detail od on o.orderID = od.orderID
join Customer c on o.customerID = c.customerID
Types of join can be: join, inner join, right/left join. It depends on you what do you want to achive i.e if you want to exclude/include null references. But the structure is the same.

How to create SQL subquery ON JOIN using multiple tables

I have the folowing tables.
ORDER
OrderNumber
CustomerNumber
EmployeeNumber
OrderDate
CUSTOMER
CustomerNumber
Name
Address
EMPLOYEE
EmployeeNumber
Name
Address
ORDERDETAIL
OrderNumber
Qty
Description
Price
Let say ORDERDETAIL table has 10 records
I would like to write a query that will return 10 records from ORDERDETAIL table to include Employee name, employee address, customer name, customer address and and order Date.
I know that I could write a query and use INNER JOIN to get the info from ORDER table, but how do you create the rest of query to get the info from the CUSTOMER and EMPLOYEE tables.
SELECT *
FROM OrderDetail D
INNER JOIN Order O
ON D.OrderNumber = O.OrderNumber;
Just add some more joins...
SELECT *
FROM OrderDetail D
JOIN Order USING (OrderNumber)
JOIN Customer USING (CustomerNumber)
JOIN Employee USING (EmployeeNumber)
You might want to re-order the JOINs in order to have the smallest tables first, as this could provide you with some performance boost (depending on your server's version, the most recent will optimize the join for you and might actually execute the joins in the "probably best" way).
Also, in the MySQL dialect at least, JOIN implicitly expands to INNER JOIN, and writing
A JOIN B USING (COL)
is equivalent to writing
A JOIN B ON (A.COL = B.COL)
SELECT *
FROM OrderDetail D
INNER JOIN Order O ON D.OrderNumber = O.OrderNumber
INNER JOIN Eployee E on O.EployeeNumber = E.EployeeNumber
INNER JOIN Customer C on O.CustomerNumber = C.CustomerNumber
if you have foreign key reference between
ORDER.EmployeeNumber and EMPLOYEE.EmployeeNumber
ORDER.CustomerNumber and CUSTOMER.CustomerNumber
then try this
SELECT
E.name AS employeeName,
E.Address AS employeeAddress,
C.name AS customerName,
C.Address AS customerAddress.
O.OrderDate
FROM OrderDetail D
INNER JOIN Order O ON D.OrderNumber = O.OrderNumber
INNER JOIN EMPLOYEE E ON E.EmployeeNumber = 0.EmployeeNumber
INNER JOIN CUSTOMER C ON C.CustomerNumber= 0.CustomerNumber
LIMIT 0,10