MySQL Query extremely slow - mysql

The following query takes too much time (0.8169sec at the moment) to show 20 entries and i can't find the reason why...
SELECT
`Order`.ID,
Order_Type.Description as OrderTypeDescription,
`Order`.OrderType as OrderType,
DATE_FORMAT(`Order`.InsertDate, '%d.%m.%Y') as OrderInsertDate,
round(sum(Item_Price.Amount),2) as OrderAmount,
c1.ID as buyerCustomerId,
c2.ID as sellerCustomerId,
c1.CompanyName as BuyerCompany,
c2.CompanyName as SellerCompany,
c1.ID as BuyerCustomer,
c2.ID as SellerCustomer
FROM `Order`
INNER JOIN Order_Type ON Order_Type.ID=`Order`.OrderType
INNER JOIN Customer as c1 ON c1.ID=`Order`.BuyerCustomer
INNER JOIN Customer as c2 ON c2.ID=`Order`.SellerCustomer
INNER JOIN Item ON Item.`Order`=`Order`.ID
INNER JOIN Item_Price ON Item_Price.Item=Item.ID
GROUP BY `Order`.ID,OrderType,OrderTypeDescription,buyerCustomerId,sellerCustomerId,BuyerCustomer,SellerCustomer
ORDER BY `Order`.ID DESC
LIMIT 20
EXPLAIN shows the following output: http://pastebin.com/5f9QYizq
I am not really good in optimizing queries, but i think the reason for the bad performance could be the join (and the sum) on the item and the item_price table, because there are a a lot of rows in both tables (item: 16974, item_price: 23981) as each item has one or more item_prices which sum up to order amount.
Any ideas how to make this query faster?

You might try using correlated subqueries instead of group by:
SELECT o.ID, ot.Description as OrderTypeDescription, ot.OrderType as OrderType,
DATE_FORMAT(o.InsertDate, '%d.%m.%Y') as OrderInsertDate,
(SELECT round(sum(ip.Amount), 2)
FROM Item i INNER JOIN
Item_Price ip
ON ip.Item = i.ID
WHERE i.`Order` = o.ID
) as OrderAmount,
c1.ID as buyerCustomerId,
c2.ID as sellerCustomerId,
c1.CompanyName as BuyerCompany,
c2.CompanyName as SellerCompany,
c1.ID as BuyerCustomer,
c2.ID as SellerCustomer
FROM `Order` o INNER JOIN
Order_Type ot
ON ot.ID = o.OrderType INNER JOIN
Customer c1
ON c1.ID = o.BuyerCustomer INNER JOIN
Customer c2
ON c2.ID = `Order`.SellerCustomer
ORDER BY o.ID DESC
LIMIT 20;
This should save on the GROUP BY overhead.
You could even move the LIMIT to a subquery, assuming that the joins are not filtering any rows:
SELECT o.ID, ot.Description as OrderTypeDescription, ot.OrderType as OrderType,
DATE_FORMAT(o.InsertDate, '%d.%m.%Y') as OrderInsertDate,
(SELECT round(sum(ip.Amount), 2)
FROM Item i INNER JOIN
Item_Price ip
ON ip.Item = i.ID
WHERE i.`Order` = o.ID
) as OrderAmount,
c1.ID as buyerCustomerId,
c2.ID as sellerCustomerId,
c1.CompanyName as BuyerCompany,
c2.CompanyName as SellerCompany,
c1.ID as BuyerCustomer,
c2.ID as SellerCustomer
FROM (SELECT o.*
FROM `Order` o
ORDER BY o.id DESC
) o INNER JOIN
Order_Type ot
ON ot.ID = o.OrderType INNER JOIN
Customer c1
ON c1.ID = o.BuyerCustomer INNER JOIN
Customer c2
ON c2.ID = `Order`.SellerCustomer
ORDER BY o.ID DESC
LIMIT 20;

Related

How do i sub query two joins?

I have created two queries that both return the required results independent of each other. I am trying to join them to have the returned values be customerName, Amount Ordered, and Amount Paid.
Currently, this query works but only returns the customerName. How can it get the query to return the other two columns?
SELECT c1.customerName
FROM
(SELECT cc.customerName, ROUND(SUM(od.priceEach * od.quantityOrdered), 2) as '$ Amount Ordered'
FROM customers cc
INNER JOIN orders o ON o.customerNumber = cc.customerNumber
INNER JOIN orderdetails od ON od.orderNumber = o.orderNumber
GROUP BY cc.customerName
) c1
INNER JOIN
(SELECT c.customerName, ROUND(SUM(p.amount), 2) as 'Total $ Amount Paid'
FROM customers c
INNER JOIN payments p ON p.customerNumber = c.customerNumber
GROUP BY c.customerName
) c2
WHERE c1.customerName = c2.customerName
GROUP BY c1.customerName
ORDER BY c1.customerName;
this should select the others column
SELECT c1.customerName, c1.Amount_Ordered as '$ Amount Ordered', c2.Total_Amount_Paid as 'Total $ Amount Paid'
FROM
(SELECT cc.customerName, ROUND(SUM(od.priceEach * od.quantityOrdered), 2) as Amount_Ordered
FROM customers cc
INNER JOIN orders o ON o.customerNumber = cc.customerNumber
INNER JOIN orderdetails od ON od.orderNumber = o.orderNumber
GROUP BY cc.customerName
) c1
INNER JOIN
(SELECT c.customerName, ROUND(SUM(p.amount), 2) as Total_Amount_Paid
FROM customers c
INNER JOIN payments p ON p.customerNumber = c.customerNumber
GROUP BY c.customerName
) c2
WHERE c1.customerName = c2.customerName
GROUP BY c1.customerName
ORDER BY c1.customerName;
simply add them to the select section:
SELECT c1.customerName, C1.amountOrdered, C2.amountPaid FROM ...
And one more word of advice - DONT use whitespace or special signs like $ in your column names, it is bad practice. I think it's a mistake that mySql even allows it

How can I select the second minimal value within a inner join?

I have this query
select c.id, c.name, c.email, c.totalpets, min(p.date_created) as first_order,
min(p.weight) as min_weight_bought,
max(p.weight) as max_weight_bought,
count(p.ordernumber) as total_orders
from orders p
inner join customers c
on p.customer_id = c.id
where p.approved = 1
and c.totalpets >= 1
group by c.id
having total_orders > 1
Note that first_order gives me the first result of the row, right? I am trying to get customer first order and customer second order. How can i do that within this inner join?
Thanks
SELECT c1.id,
c1.name,
c1.email,
c1.totalpets,
p1.date_created
FROM orders p1
INNER JOIN customers c1
ON p1.customer_id = c1.id
WHERE
(
SELECT COUNT(*)
FROM orders p2
INNER JOIN customers c2
ON p2.customer_id = c2.id
WHERE c2.id = c1.id AND p2.date_created <= p1.date_created
) <= 2
ORDER BY c1.id;
Here is a running demo which shows a simplified version of the above query (and simplified data set) in action:
SQLFiddle

inner join 4 tables with group, order by, having clause

I have 4 table and i want to extract: id, nume, localitate, masina_id, nr_inmatriculare, an_fabricatie, rafinarie, marca, and sum (quantity+deliver_quantity) as total_quantity group by an_fabricatie , Order by marca, and put some having clouse.
I don’t know how to make this.
My query is as bellow , but I think isn't correct.
select c.id, c.nume,c.localitate,l.masina_id, i.nr_inmatriculare, i.an_fabricatie,
i.rafinarie, m.marca from clienti c inner join livrari l on c.id = l.id inner join incarcari I on l.incarcare_id = l.livrari_id inner join masina m on i.id_marca = m.id, sum(select quantity, deliver_quantity) as total_quantity group by an_fabricatie having quantity >1000 order by marca;
Incarcari table
Id|livrari_id|id_marca|nr_inmatriculare|an_fabricatie|rafinarie|aviz_incarcare|quantity|
Livrari table
Id|masina_id|client_id|incarcare_id|deliver_quantity|aviz_livrare
Masini table
Id|numar_inmatriculare|marca|an_fabricatie|
Clienti table
Id|nume|localitate|date_add|date_upd|
SELECT c.id, c.nume, c.localitate, l.masina_id, i.nr_inmatriculare, i.an_fabricatie, i.rafinarie, m.marca, (SUM(i.quantity) + SUM(l.deliver_quantity)) AS total_quantity
FROM clienti c
INNER JOIN livrari l ON c.id = l.id
INNER JOIN incarcari i ON l.incarcare_id = i.livrari_id
INNER JOIN masini m ON i.id_marca = m.id
GROUP BY i.an_fabricatie, c.id, c.nume,c.localitate,l.masina_id, i.nr_inmatriculare, i.rafinarie, m.marca
HAVING i.quantity > 1000
ORDER BY m.marca DESC;

Using GROUP_CONCAT on multiple fields

Here's a picture of my database structure:
With help from users on here I've managed to put together quite a complex SQL statement using GROUP_CONCAT:
SELECT
t1.Name AS Teacher_Name,
t2.Name AS Observer_Name,
o.Datetime AS Datetime,
o.Type AS Type,
o.Year_Group AS Year_Group,
o.Class_Name AS Class_Name,
c.Title AS Course_Name,
GROUP_CONCAT(l.Title) AS Focus,
o.Achievement_Grade AS Achievement_Grade,
o.Behaviour_Grade AS Behaviour_Grade,
o.Teaching_Grade AS Teaching_Grade,
GROUP_CONCAT(cl1.Title) AS Positive,
GROUP_CONCAT(cl2.title) AS Development,
o.Notes AS Notes
FROM observations o
LEFT JOIN teachers t1
ON o.Teacher_ID = t1.Teacher_ID
LEFT JOIN teachers t2
ON o.Observer_ID = t2.Teacher_ID
LEFT JOIN courses c
ON o.Course_ID = c.Course_ID
LEFT JOIN foci f
ON o.ID = f.Observation_ID
LEFT JOIN focus_labels l
on f.focus_id = l.id
LEFT JOIN criteria c1
ON o.ID = c1.Observation_ID
LEFT JOIN criteria_labels cl1
on c1.Criteria_ID = cl1.ID AND c1.Type = 'P'
LEFT JOIN criteria c2
ON o.ID = c2.Observation_ID AND c2.Type = 'D'
LEFT JOIN criteria_labels cl2
on c2.Criteria_ID = cl2.ID
GROUP BY o.id
ORDER BY `Datetime` DESC";
This appears to work OK, apart from the fact that Focus, Positive and Development are each repeated depending on the field that has the highest number of concatenations in.
For example, if Positive has Pace,Progress,Attainment but Focus is only Appraisal, it'll be repeated three times (Appraisal,Appraisal,Appraisal).
I've looked this up and I think it could be because I need to GROUP each of these GROUP_CONCAT JOINs. However, I have no idea how to go about this.
Can anyone help? Thanks in advance,
GROUP_CONCAT has DISTINCT attribute that can be applied to remove duplicates.
SELECT
t1.Name AS Teacher_Name,
t2.Name AS Observer_Name,
o.Datetime AS Datetime,
o.Type AS Type,
o.Year_Group AS Year_Group,
o.Class_Name AS Class_Name,
c.Title AS Course_Name,
GROUP_CONCAT(DISTINCT l.Title) AS Focus,
o.Achievement_Grade AS Achievement_Grade,
o.Behaviour_Grade AS Behaviour_Grade,
o.Teaching_Grade AS Teaching_Grade,
GROUP_CONCAT(cl1.Title) AS Positive,
GROUP_CONCAT(cl2.title) AS Development,
o.Notes AS Notes
FROM observations o
LEFT JOIN teachers t1
ON o.Teacher_ID = t1.Teacher_ID
LEFT JOIN teachers t2
ON o.Observer_ID = t2.Teacher_ID
LEFT JOIN courses c
ON o.Course_ID = c.Course_ID
LEFT JOIN foci f
ON o.ID = f.Observation_ID
LEFT JOIN focus_labels l
on f.focus_id = l.id
LEFT JOIN criteria c1
ON o.ID = c1.Observation_ID
LEFT JOIN criteria_labels cl1
on c1.Criteria_ID = cl1.ID AND c1.Type = 'P'
LEFT JOIN criteria c2
ON o.ID = c2.Observation_ID AND c2.Type = 'D'
LEFT JOIN criteria_labels cl2
on c2.Criteria_ID = cl2.ID
GROUP BY o.id
ORDER BY `Datetime` DESC";

Multiple inner joins to get a complex report, not working

For the schema below, I need to get this report
This is what I have
select c.name, sr.name, count(o.order_id)
from contact c
INNER JOIN accounts a
ON c.account_id=a.account_id
INNER JOIN sales_reps sr
ON a.sales_rep_id =sr.sales_rep_id
INNER JOIN orders o
ON a.account_id =o.account_id
where o.order_id in (
select SUM(oi.quantity*p.price) from
order_items oi INNER JOIN parts p
on oi.part_id =p.part_id
)
group by a.account_id, c.name
But this does not give any results.
Please help.
Your where condition is not right, how should be a order_id equal a sum?
Try the below:
select
c.name, sr.name, COUNT(o.order_id), SUM(op.order_total)
FROM
contact c
INNER JOIN
accounts a ON c.account_id = a.account_id
INNER JOIN
sales_reps sr ON a.sales_rep_id = sr.sales_rep_id
INNER JOIN
orders o ON a.account_id = o.account_id
INNER JOIN
(SELECT
oi.order_id, SUM(oi.quantity * p.price) AS order_total
FROM
order_items oi
INNER JOIN
parts p ON oi.part_id = p.part_id
GROUP BY
oi.order_id
) op ON o.order_id = op.order_id
WHERE o.delivery_data >= CURDATE()
GROUP by c.contact_id
It won't give results as your WHERE ... IN SELECT is based on a query returning a sum() value which will not equal a key (most likely), or incorrect at best... and since you are dealing with a quantity and price which will have decimal precision (typically), you won't even get that to match even LESS likely...
I would swap the query around to pre-qualify the orders within a given date in question and sum that... THEN join to rest...
select
c.name,
sr.name,
PreQualified.NumberOrders,
PreQualified.OrderTotal
from
( select
o.Account_ID,
count( distinct o.order_id ) as NumberOrders,
sum( oi.quantity * p.price ) as OrderTotal
from
orders o
join order_items oi
on o.order_id = oi.order_id
join parts p
on oi.part_id = p.part_id
where
o.Delivery_Date >= CURDATE()
group by
o.Account_ID ) as PreQualified
JOIN Accounts a
on PreQualified.Account_ID = a.Account_ID
Join Contact C
on a.Account_ID = c.Account_ID
JOIN Sales_Reps sr
ON a.sales_rep_id = sr.sales_rep_id
If you want to count records use
count(*)
Instead of
count(o.order_id)