How to convert SQL subquery into Join Clause? - mysql

Good day everyone,
I have been attempting to convert the following SQL statement into a join clause, however I have been unable to figure out how to do it and was wondering if I could get some help.
Here is the statement:
SELECT OrderID FROM Orders
WHERE OrderDate = (SELECT orderDate FROM Orders WHERE OrderID = 10280);
I am essentially trying to get all orderIDs that were placed on the same date as the Order with OrderID 10280.
Thanks,

Try this:
SELECT o.OrderId
FROM Orders o
JOIN Orders ord
ON o.OrderDate = ord.OrderDate
WHERE ord.OrderID = 10280;
You can have a better understanding from here: https://www.sqlservertutorial.net/sql-server-basics/sql-server-self-join/#:~:text=A%20self%20join%20allows%20you,join%20or%20left%20join%20clause.

Related

Can I use sub queries and a join in the same statement in MYSQL

This problem has left me clueless. I am trying to use a Join in mysql and a subquery and I keep getting a syntax error.
The statement in question is
SELECT Customer.customer_id, Customer.name, Order.address FROM Customer
WHERE customer_id = (SELECT customer_id FROM Order WHERE customer_id = "625060836f7496e9fce3bbc6")
INNER JOIN Order ON Customer.customer_id=Order.customer_id;
I have tried to just use the query without the Subquery and it works fine.
SELECT Customer.customer_id, Customer.name, Order.address FROM Customer
INNER JOIN Order ON Customer.customer_id=Order.customer_id;
Removing the join but keeping the subquery also works.
SELECT Customer.customer_id, Customer.name, Order.address FROM Customer
WHERE customer_id = (SELECT customer_id FROM Order WHERE customer_id = "625060836f7496e9fce3bbc6")
Only using both the subquery and the join results in a syntax error
I cannot seem to find the error.
What have I done wrong here.
Thanks in advance
The secret is to get the syntax right!
When querying more than one table it's good practice to use aliases to reference them and where multiple tables share the same column names, also string literals should be delimited with single 'quotes'.
In this specific example however the subquery is superfluous, just use the string literal directly in the where clause.
SELECT c.customer_id, c.name, o.address
FROM Customer c
JOIN Order o ON c.customer_id = o.customer_id
WHERE c.customer_id = (
SELECT customer_id
FROM Order
WHERE customer_id = '625060836f7496e9fce3bbc6'
);

Mysql select query count & Distinct are not working properly

I am developing an eCommerce website using Laravel 8. I write the following script for find out total price & total quantity under a single order number. From following script getting the ERROR where is the problem please help me.
*At first I write row mysql then i will convert laravel query Builder.
SELECT COUNT (total_price) as totaPrice, COUNT (productqty) as proQnty
FROM (SELECT DISTINCT order_id FROM orderDetails)
LEFT JOIN ordertbl
ON ordertbl.id = orderDetails.order_id;
I guess you want to sum the prices and quantities, so use SUM() aggregate function.
Also you should do a LEFT join of ordertbl to orderDetails and not the other way around:
SELECT ot.id,
SUM(od.total_price) AS totaPrice,
SUM(od.productqty) AS proQnty
FROM ordertbl ot LEFT JOIN orderDetails od
ON ot.id = od.order_id
WHERE ot.id = ?
GROUP BY ot.id;
Or, without a join:
SELECT SUM(total_price) AS totaPrice,
SUM(productqty) AS proQnty
FROM orderDetails
WHERE order_id = ?;
Replace ? with the id of the order that you want.
In Your raw in missing the tablename alis for the subquery ..
Your raw query should be
SELECT COUNT(total_price) as totaPrice, COUNT(productqty) as proQnty
FROM (
SELECT DISTINCT order_id FROM orderDetails
) T
LEFT JOIN ordertbl ON ordertbl.id = T.order_id;

Two Select Queries on same table

I am struggling to find an answer to this issue.
I have a table where I can have multiple order ids for one customer (email)
email (unique), order_id
I need to make a query where I pass in any order_id for a customer, and it returns ALL their orders.
I have two select queries I need to combine into one query to save on load time.
SELECT email FROM orders WHERE order_id = '1234567890'
SELECT order_id FROM orders WHERE email = 'email_found_from_first_query'
An old school way of using in can be used here:
SELECT order_id
FROM orders
WHERE email IN (
SELECT email
FROM orders
WHERE order_id = '1234567890'
)
query is little expensive.
One method uses a correlated subquery:
select o.order_id
from orders o
where o.email = (select o2.email from orders o2 where order_id = '1234567890')
This seems best suited for a simple JOIN. https://www.mysqltutorial.org/mysql-join/
SELECT orig_order.email, all_orders.order_id
FROM orders as orig_order
JOIN orders as all_orders ON orig_order.email = all_orders.email
WHERE orig_order.order_id = '1234567890'

SQL beginner practice problems

Given two tables, orders (order_id, date, $, customer_id) and customers (ID, name)
Here's my method but I'm not sure if it's working & I'd like to know if there's faster/better way of solving these problems:
1) find out number of customers who made at least one order on date 7/9/2018
Select count (distinct customer_id)
From
(
Select customer_id from orders a
Left join customer b
On a.customer_id = b.ID
Group by customer_id,date
Having date = 7/9/2018
) a
2) find out number of customers who did not make an order on 7/9/2018
Select count (customer_id) from customer where customer_id not in
(
Select customer_id from orders a
Left join customer b
On a.customer_id = b.ID
Group by customer_id,date
Having date = 7/9/2018
)
3) find the date with most sales between 7/1 and 7/30
select date, max($)
from (
Select sum($),date from orders a
Left join customer b
On a.customer_id = b.ID
Group by date
Having date between 7/1 and 7/30
)
Thanks,
For problem 1, a valid solution might look like this:
SELECT COUNT(DISTINCT customer_id) x
FROM orders
WHERE date = '2018-09-07'; -- or is that '2018-07-09' ??
For problem 2, a valid solution might look like this:
SELECT COUNT(*) x
FROM customer c
LEFT
JOIN orders o
ON o.customer_id = x.customer_id
AND o.date = '2018-07-09'
WHERE o.crder_id IS NULL;
Assuming there are no ties, a valid solution to problem 3 might look like this:
SELECT date
, COUNT(*) sales
FROM orders
WHERE date BETWEEN '2018-07-01' AND '2018-07-30'
GROUP
BY date
ORDER
BY sales DESC
LIMIT 1;
The default format for a date in MySQL is YYYY-MM-DD, although this can be customized. You have to put quotes around it, otherwise it's treated as an arithmetic expression.
And none of your queries need to join with the customer table. The customer ID is already in the orders table, and you're not returning any info about the customers (like the name or address), you're just counting them.
1) You don't need the subquery or grouping.
SELECT COUNT(DISTINCT customer_id)
FROM orders
WHERE date = '2018-07-09'
2) Again, you don't need GROUP BY in the subquery. There's also a better pattern than NOT IN to get the count of non-matching rows.
SELECT COUNT(*)
FROM customer AS c
LEFT JOIN order AS o on c.id = o.customer_id AND o.date = '2018-07-09'
WHERE o.id IS NULL
See Return row only if value doesn't exist for various patterns to do this.
3) You can't use MAX($) in the outer query because the inner query doesn't return a column with that name. But even if you fix that, it still won't work, because the date column won't necessarily come from the same row that has the maximum. See SQL select only rows with max value on a column for more explanation of this.
You don't need a subquery at all. Use a query that returns the total sales for each day, then use ORDER BY to get the highest one.
SELECT date, SUM($) AS total_sales
FROM orders
WHERE date BETWEEN '2018-07-01' AND '2017-07-30'
GROUP BY date
ORDER BY total_sales DESC
LIMIT 1
If "most sales" is supposed to mean "most number of sales", replace SUM($) with COUNT(*).

SQL join returns all values from the wrong table

I am new to SQL and I cannot figure out why my SQL result returns all data from the wrong table. I want to receive all data from product table but I want to filter the results so it does not show those results that have some value in another table.
My SQL statement is:
SELECT *
FROM orders
JOIN products
ON orders.product_id=products.product_id
AND NOT order_date=somedate;
This query returns everything from the orders table where somedate is not the given value but I want to get everything from the products table if orders table does not have the given somedate as value (when the product is not reserved).
Edit: thanks for the help everyone! each answer worked perfectly for me with some slight modifications :)
You can get products which don't have orders of a certain criteria (order_date != somedate) like this:
SELECT p.*
FROM products p
LEFT JOIN orders o ON o.product_id = p.product_id AND order_date != somedate
WHERE o.id IS NULL
Different orders could have different dates. If you want products that were not ordered on a particular date, then try phrasing the query like this:
If I understand correctly, your original query returned all products with multiple orders, because some orders were on that date and some were not.
select p.*
from product p
where not exists (select 1
from orders o
where o.product_id = p.product_id
and o.order_date = somedate)
Not sure I got your question right, but you can try this:
SELECT p.*
FROM orders
JOIN products
ON orders.product_id=products.product_id
WHERE order_date<>somedate;