MySQL , JOIN , When total = 1 - mysql

i need little help in writing the MYSQL Query.
i want to retreive the data from 3 tables, but i want to retreive the data from 3rd table only if the count() value is equals to 1.
please see the below query.
SELECT count(orderdetails.orderId) as total,gadgets.*,orders.* FROM orders
JOIN orderdetails ON orders.orderId = orderdetails.orderId
CASE total WHEN 1 THEN (JOIN gadgets ON gadgets.gadgetId = orders.gadgetId)
GROUP BY orders.orderId
ORDER BY orders.orderId DESC;
mysql always gives me an error, and i couldnt find any solution over internet.

Just add a Simple Condition in Join, and it would work (Of course you have make it Left Join).
SELECT count(orderdetails.orderId) as total,gadgets.*,orders.* FROM orders
JOIN orderdetails ON orders.orderId = orderdetails.orderId
LEFT JOIN gadgets ON gadgets.gadgetId = orders.gadgetId
and total=1 --Simple Logic
GROUP BY orders.orderId
ORDER BY orders.orderId DESC;

SELECT
g.*, o.*
FROM
orders AS o
JOIN
( SELECT orderId
FROM orderdetails
GROUP BY orderId
HAVING COUNT(*) = 1
) AS od
ON o.orderId = od.orderId
JOIN gadgets AS g
ON g.gadgetId = o.gadgetId
ORDER BY
o.orderId DESC ;

You can join the table and get only results having total = 1
SELECT count(orderdetails.orderId) as total,gadgets.*,orders.* FROM orders
JOIN orderdetails ON orders.orderId = orderdetails.orderId
JOIN gadgets ON gadgets.gadgetId = orders.gadgetId
GROUP BY orders.orderId
HAVING total = 1
ORDER BY orders.orderId DESC;
HTH

Related

The output of MySQL results shows no results in one column

Whenever I use this query:
SELECT Orders.SKU AS SKU,
(COUNT(*) * 100 / (SELECT COUNT(*) FROM Orders INNER JOIN RMA ON Orders.OrderID = RMA.OrderID)) AS Returned_Percentage
FROM Orders
INNER JOIN RMA
ON Orders.OrderID = RMA.OrderID
INNER JOIN Customers
ON Customers.CustomerID = Orders.CustomerID
GROUP BY SKU, Description
ORDER BY Returned_Percentage DESC
I get the results that I need.
Successful Results
But when I add a column with a larger VARCHAR(50), the results leave out one column of results.
SELECT Orders.SKU AS SKU,
(COUNT(*) * 100 / (SELECT COUNT(*) FROM Orders INNER JOIN RMA ON Orders.OrderID = RMA.OrderID)) AS Returned_Percentage, **Orders.Description**
FROM Orders
INNER JOIN RMA
ON Orders.OrderID = RMA.OrderID
INNER JOIN Customers
ON Customers.CustomerID = Orders.CustomerID
GROUP BY SKU, Description
ORDER BY Returned_Percentage DESC
enter image description here
Can anyone point me in the right direction to obtaining the results with the records stored properly in the columns?
Thank you!
I add the query:
SELECT Orders.SKU AS SKU,
(COUNT(*) * 100 / (SELECT COUNT(*) FROM Orders INNER JOIN RMA ON Orders.OrderID = RMA.OrderID)) AS Returned_Percentage, Orders.Description
FROM Orders
INNER JOIN RMA
ON Orders.OrderID = RMA.OrderID
INNER JOIN Customers
ON Customers.CustomerID = Orders.CustomerID
GROUP BY SKU, Description
ORDER BY Returned_Percentage DESC
but receive empty columns of records.

How to answer a question that uses multiple tables without joins? SQL

Is there a way to answer this question without using joins?
Write a query that finds, for each customer X, another customer Y who has ordered at least one product in common with X. Find all such pairs of Customers (X, Y) and against each pair, the number of overlapping products. The query should thus have three columns. Order the results by the number of overlapping products.
The question uses the https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
database.
Using joins, I can answer the question like this:
O2.CustomerID AS Cust2,
COUNT(*) AS OverlappingProd
FROM (SELECT O.CustomerID, OD.ProductID
FROM Orders AS O
JOIN OrderDetails AS OD
ON OD.orderid = o.orderid) AS O1
JOIN(SELECT O.CustomerID, OD.ProductID
FROM Orders AS O
JOIN OrderDetails AS OD
ON OD.orderid = o.orderid) AS O2
ON O2.ProductID = O1.ProductID
AND O2.CustomerID > O1.CustomerID
GROUP BY
O1.CustomerID,
O2.CustomerID
ORDER BY COUNT(*) DESC;
Is there a way to answer it not using the JOIN function? Thank you for your time and consideration.
I cannot think of a way of doing this without any joins. You can express this in SQL using cross join and exists, so the following comes close:
select c1.customerid, c2.customerid,
(select count(*)
from products p
where exists (select 1
from orderdetails od
where od.productid = p.productid and
exists (select 1
from orders o
where o.orderid = od.orderid and
o.customerid = c1.customerid
)
) and
exists (select 1
from orderdetails od
where od.productid = p.productid and
exists (select 1
from orders o
where o.orderid = od.orderid and
o.customerid = c2.customerid
)
)
) as num_products
from customers c1 cross join
customers c2
where c1.customerid < c2.customerid;
Although this syntax will work in many databases, the nested correlation clauses are not supported in MySQL. So, even accepting the CROSS JOIN, this does not work in MySQL.
The reason why a JOIN seems necessary is to get two independent customer ids in the result set.

converting a sql query to subquery

I am trying to determine the customers spending behavior by writing a query to select the top 10 highest spenders.
I have the following query and it works fine:
SELECT c.CustomerID
, SUM(Quantity * UnitPrice) Total_Spent
FROM Orders o
JOIN OrderDetails d
ON d.OrderID = o.OrderID
JOIN Customers c
ON c.CustomerID = o.CustomerID
GROUP
BY c.CustomerID
ORDER
BY Total_Spent
limit 10;
However, I want to create a subquery instead of having this complicated one. I have tried the following but it doesn't work:
SELECT Customers.CustomerID
FROM Customers
JOIN (
SELECT SUM(Quantity *UnitPrice) as Total_Spent
FROM Orders
JOIN OrderDetails
ON Orders.OrderID = OrderDetails.OrderID) Orders
ON Orders.CustomerID = Customers.CustomerID
GROUP BY Customers.CustomerID
ORDER BY Total_Spent
LIMIT 10;
I don't know what the problem is. (I am kinda new in SQL)
You can simplify your query because you don't need the customers table. That and table aliases should make your query simpler:
SELECT o.CustomerID, SUM(od.Quantity * od.UnitPrice) as Total_Spent
FROM Orders o JOIN
OrderDetails od
ON o.OrderID = od.OrderID
GROUP BY o.CustomerID
ORDER BY Total_Spent DESC
LIMIT 10;

SQL Get all orders which contain exclusively one kind of item

In this Database I want to count the number of orders that contain only products of a certain category.
I know how to count all orders that also contain items of a certain category, i.e. category 1:
SELECT Count(DISTINCT orderdetails.orderid) AS "AllCat1"
FROM orderdetails
INNER JOIN orders
ON orderdetails.orderid = orders.orderid
AND orderdetails.productid IN (SELECT DISTINCT productid
FROM products
WHERE categoryid = 1)
WHERE orderdate BETWEEN "1996-12-01" AND "1996-12-31";
I am having trouble finding an elegant way to get all orders that contain only category 1 items. I tried selecting all OrderIDs and grouping them by OrderID AND CategoryID:
SELECT *
FROM orderdetails
INNER JOIN orders
ON orderdetails.orderid = orders.orderid
AND orderdate BETWEEN "1996-12-01" AND "1996-12-31"
INNER JOIN products
ON orderdetails.productid = products.productid
GROUP BY orderdetails.orderid,
categoryid;
But I have no idea how to count all OrderIDs that contain category 1 items exclusively. Is my approach right? Or is there a better way to do it (Which I am sure there is)
You can use group by and having . . . but you need two levels. To get the orders that are all in one (or a set of categories) by doing:
SELECT o.orderId
FROM orders o JOIN
orderdetails od
ON od.orderid = o.orderid JOIN
products p
ON p.productid = od.productid
WHERE o.orderdate BETWEEN '1996-12-01' AND '1996-12-31'
GROUP BY o.orderId
HAVING SUM(CASE WHEN p.categoryid IN (1) THEN 1 ELSE 0 END) = COUNT(*);
The count needs a subquery:
SELECT COUNT(*)
FROM (SELECT o.orderId
FROM orders o JOIN
orderdetails od
ON od.orderid = o.orderid JOIN
products p
ON p.productid = od.productid
WHERE o.orderdate BETWEEN '1996-12-01' AND '1996-12-31'
GROUP BY o.orderId
HAVING SUM(CASE WHEN p.categoryid IN (1) THEN 1 ELSE 0 END) = COUNT(*)
) o;
You can do filtering using HAVING clause. We basically Count the order details rows where category is 1 for an order. It should be equal to the total count of rows for that order. This would ensure that all the categories in an order is 1 only.
SELECT od.orderid
FROM orderdetails AS od
INNER JOIN orders AS o
ON od.orderid = o.orderid
AND o.orderdate BETWEEN "1996-12-01" AND "1996-12-31"
INNER JOIN products AS p
ON od.productid = p.productid
GROUP BY od.orderid
HAVING COUNT(CASE WHEN p.categoryid = 1 THEN 1 END) = COUNT(*)
It is advisable to use Aliasing in case of multi-table queries for Code clarity and readability

Getting data from multiple tables in mysql using joins ends in wrong data

I need to select the customer and product code and the date on which the order was made, but I'm having some trouble with the join orders.
My SQL select:
select c.customerNumber, p.productCode, o.orderDate as data_compra
from customers as c inner join orders as o
inner join products as p
where p.productCode =
any (
select p2.productCode from products as p2
inner join orders as o
inner join orderdetails as odt
where o.orderNumber = odt.orderNumber and
p2.productCode = odt.productCode
)
and o.orderNumber =
any (
select o2.orderNumber from orders as o2
inner join orderdetails as odt
where o.orderNumber = odt.orderNumber and
p.productCode = odt.productCode
)
Two simple joins should do what you want:
select
c.customerNumber,
d.productCode,
o.orderDate
from customer c
join orders o on o.customerNumber = c.customerNumber
join orderdetails d on d.orderNumber = o.orderNumber
In the code you're asking to inner join two tables but not specifying the relationship. You need to do so SQL can relate and match the rows in each table.
You do this with the ON keyword.
I suggest you watch this video and read this article before continuing