MySQL LIMIT in a Correllated Subquery - mysql

I have a correlated subquery that will return a list of quantities, but I need the highest quantity, and only the highest. So I tried to introduce an order by and a LIMIT of 1 to achieve this, but MySQL throws an error stating it doesn't yet support limits in subqueries. Any thoughts on how to work around this?
SELECT Product.Name, ProductOption.Name, a.Qty, a.Price, SheetSize.UpgradeCost,
FinishType.Name, FinishOption.Name, FinishTierPrice.Qty, FinishTierPrice.Price
FROM `Product`
JOIN `ProductOption`
ON Product.idProduct = ProductOption.Product_idProduct
JOIN `ProductOptionTier` AS a
ON a.ProductOption_idProductOption = ProductOption.idProductOption
JOIN `PaperSize`
ON PaperSize.idPaperSize = ProductOption.PaperSize_idPaperSize
JOIN `SheetSize`
ON SheetSize.PaperSize_idPaperSize = PaperSize.idPaperSize
JOIN `FinishOption`
ON FinishOption.Product_idProduct = Product.idProduct
JOIN `FinishType`
ON FinishType.idFinishType = FinishOption.Finishtype_idFinishType
JOIN `FinishTierPrice`
ON FinishTierPrice.FinishOption_idFinishOption = FinishOption.idFinishOption
WHERE Product.idProduct = 1
AND FinishTierPrice.idFinishTierPrice IN (SELECT FinishTierPrice.idFinishTierPrice
FROM `FinishTierPrice`
WHERE FinishTierPrice.Qty <= a.Qty
ORDER BY a.Qty DESC
LIMIT 1)

This is a variation of the greatest-n-per-group problem that comes up frequently.
You want the single row form FinishTierPrice (call it p1), matching the FinishOption and with the greatest Qty, but still less than or equal to the Qty of the ProductOptionTier.
One way to do this is to try to match a second row (p2) from FinishTierPrice that would have the same FinishOption and a greater Qty. If no such row exists (use an outer join and test that it's NULL), then the row found by p1 is the greatest.
SELECT Product.Name, ProductOption.Name, a.Qty, a.Price, SheetSize.UpgradeCost,
FinishType.Name, FinishOption.Name, FinishTierPrice.Qty, FinishTierPrice.Price
FROM `Product`
JOIN `ProductOption`
ON Product.idProduct = ProductOption.Product_idProduct
JOIN `ProductOptionTier` AS a
ON a.ProductOption_idProductOption = ProductOption.idProductOption
JOIN `PaperSize`
ON PaperSize.idPaperSize = ProductOption.PaperSize_idPaperSize
JOIN `SheetSize`
ON SheetSize.PaperSize_idPaperSize = PaperSize.idPaperSize
JOIN `FinishOption`
ON FinishOption.Product_idProduct = Product.idProduct
JOIN `FinishType`
ON FinishType.idFinishType = FinishOption.Finishtype_idFinishType
JOIN `FinishTierPrice` AS p1
ON p1.FinishOption_idFinishOption = FinishOption.idFinishOption
AND p1.Qty <= a.Qty
LEFT OUTER JOIN `FinishTierPrice` AS p2
ON p2.FinishOption_idFinishOption = FinishOption.idFinishOption
AND p2.Qty <= a.Qty AND (p2.Qty > p1.Qty OR p2.Qty = p1.Qty
AND p2.idFinishTierPrice > p1.idFinishTierPrice)
WHERE Product.idProduct = 1
AND p2.idFinishTierPrice IS NULL

Related

How to efficiently select the rows corresponding with the highest value for a specific column?

I have a query:
SELECT * FROM `InvoiceLines`
INNER JOIN Invoices ON Invoices.`invoiceID` = InvoiceLines.`invoiceID`
INNER JOIN `DistributorOrdersTbl` ON DistributorOrdersTbl.`distOrderRecID` = Invoices.`orderID`
WHERE DistributorOrdersTbl.`distOrderRecID` = 3829
AND InvoiceLines.`qty` > 0
Which returns a number of Invoices:
I wanted to select only the invoices with the newest ID 2800. The way I ended up doing it was a bit of copy pasting:
SELECT * FROM `InvoiceLines`
INNER JOIN Invoices ON Invoices.`invoiceID` = InvoiceLines.`invoiceID`
INNER JOIN `DistributorOrdersTbl` ON DistributorOrdersTbl.`distOrderRecID` = Invoices.`orderID`
WHERE DistributorOrdersTbl.`distOrderRecID` = 3829
AND InvoiceLines.`qty` > 0
AND Invoices.invoiceID = (
SELECT MAX(Invoices.invoiceID) FROM `InvoiceLines`
INNER JOIN Invoices ON Invoices.`invoiceID` = InvoiceLines.`invoiceID`
INNER JOIN `DistributorOrdersTbl` ON DistributorOrdersTbl.`distOrderRecID` = Invoices.`orderID`
WHERE DistributorOrdersTbl.`distOrderRecID` = 3829
AND InvoiceLines.`qty` > 0
)
And sure enough, the correct invoices are returned. However it feels as though this is inefficient as I am essentially performing the query twice. What would be the best way of doing this? I tried the following but it seems this is incorrect SQL:
SELECT * FROM `InvoiceLines`
INNER JOIN Invoices ON Invoices.`invoiceID` = InvoiceLines.`invoiceID`
INNER JOIN `DistributorOrdersTbl` ON DistributorOrdersTbl.`distOrderRecID` = Invoices.`orderID`
WHERE DistributorOrdersTbl.`distOrderRecID` = 3829
AND InvoiceLines.`qty` > 0
AND Invoices.invoiceID = MAX(Invoices.invoiceID)
Which returns "Invalid use of group function".
Thanks in advance!
Assuming all invoices have invoice lines, you can use a subquery just on Invoices:
SELECT *
FROM (SELECT i.*
FROM Invoices i
WHERE i.orderID = 3829
ORDER BY i.invoiceID DESC
LIMIT 1
) i JOIN
InvoiceLines il
ON i.invoiceID = il.invoiceID JOIN
DistributorOrdersTbl d
ON d.distOrderRecID = i.orderID
WHERE il.qty > 0;

same SQL subquery with WHERE and FROM

Using the table below
It can also be easily replaced with an OUTER JOIN whenever a need arises.
The WHERE syntax is more relational model oriented.
A result of two tables JOIN'ed is a cartesian product of the tables to which a filter is applied which selects only those rows with joining columns matching.
It's easier to see this with the WHERE syntax.
SELECT Toy_name, Quantity
FROM Toy T,Hire Transaction H, Store S
WHERE S.Store_ID = T.store_id
AND t.toy_id = H.toy_id
AND t.hire_price = (SELECT max(hire_price) from Toy)
AND UPPER(S.store_suburb = ‘SCARSDALE’)
AND H.hire_date >= ’01/02/2013’
AND H.hire_date <= ’31/03/2015’;
I was able to write this. But how can I solve this using a subquery as asked?
You could avoid the sub select, by ordering your result by descending price, and then limiting the output to just one record:
SELECT Toy_name,
Sum(H.Quantity) total_quantity
FROM Toy T
INNER JOIN `Hire Transaction` H
ON H.Toy_id = t.Toy_id
INNER JOIN Store S
ON S.Store_ID = T.store_id
WHERE upper(S.store_suburb) = 'SCARSDALE'
AND H.hire_date BETWEEN '2013-02-01' AND '2015-03-31'
GROUP BY T.Toy_id
ORDER BY T.Hire_price DESC
LIMIT 1
You can try this
SELECT t.toy_name, sum(ht.quantity) quantity, max(t.hire_price) max_p
FROM toy t
INNER JOIN hire_transaction ht on t.toy_id = ht.toy_id
INNER JOIN store s on t.store_id = s.store_id
WHERE ht.hire_date between '2013-02-01' and '2015-03-31' and upper(s.store_suburb) = 'SCARSDALE'
group by t.toy_id
having max(max_p)
select h.toy_id, sum(h.Quantity) as hire_count from HireTransaction as h where h.hire_date >= ’01/02/2013’
AND h.hire_date <= ’31/03/2015’ group by h.toy_id having h.toy_id = (select toy_id from Toy where hire_price = (select max(hire_price) from Toy) and store_id = (select store_id from Store where store_suburb = 'SCARSDALE')

mysql inner join return null value,

SELECT `mpeda_fish`.`id`, `mpeda_fish`.`fish` as analysis, sum(mpeda_fishdetails.quantity) as qty
FROM (`mpeda_fishdetails`)
INNER JOIN `mpeda_scientificfish` ON `mpeda_scientificfish`.`id` = `mpeda_fishdetails`.`scientificfish`
INNER JOIN `mpeda_fish` ON `mpeda_fish`.`id` = `mpeda_scientificfish`.`fish`
INNER JOIN `mpeda_fishcatch` ON `mpeda_fishcatch`.`id` = `mpeda_fishdetails`.`fishcatch`
INNER JOIN `mpeda_harbour` ON `mpeda_harbour`.`id` = `mpeda_fishcatch`.`harbour`
WHERE `mpeda_fishcatch`.`status` = 1
ORDER BY `mpeda_fishdetails`.`id` ASC
this query gets 2 columns null value and one column gets data inside why?
You use the SUM() function. In order to get meaningful results you should have a group by clause.
SELECT `mpeda_fish`.`id`, `mpeda_fish`.`fish` as analysis, sum(mpeda_fishdetails.quantity) as qty
FROM (`mpeda_fishdetails`)
INNER JOIN `mpeda_scientificfish` ON `mpeda_scientificfish`.`id` = `mpeda_fishdetails`.`scientificfish`
INNER JOIN `mpeda_fish` ON `mpeda_fish`.`id` = `mpeda_scientificfish`.`fish`
INNER JOIN `mpeda_fishcatch` ON `mpeda_fishcatch`.`id` = `mpeda_fishdetails`.`fishcatch`
INNER JOIN `mpeda_harbour` ON `mpeda_harbour`.`id` = `mpeda_fishcatch`.`harbour`
WHERE `mpeda_fishcatch`.`status` = 1
GROUP BY `mpeda_fish`.`id`, `mpeda_fish`.`fish`
ORDER BY `mpeda_fishdetails`.`id` ASC

Difficult MySQL Statement

I've got this query but the result is wrong.
How can I use the min() statement and the Group by Statement so that I will get for each AthletenID the lowest DiszOrder?
Select
ar_Leistungen.`AthletenID`,
ar_Leistungen.`Leistung`,
ar_Leistungen.`Disziplin`,
ar_Leistungen.`Klasse`,
min(ar_Leistungen.`DiszOrder`),
ar_Athleten.`Vorname`,
ar_Athleten.`Jahrgang`,
ar_Wettkampf.`Wettkampfdatum`
from
ar_Leistungen,
ar_Athleten,
ar_Wettkampf
Where
ar_Athleten.ID = ar_Leistungen.AthletenID and
ar_Leistungen.WettkampfID = ar_Wettkampf.ID and
ar_Leistungen.`Disziplin` = '100' and
ar_Leistungen.`Leistung` > 0 and
(ar_Athleten.`Jahrgang` = '1995' or ar_Athleten.`Jahrgang` = '1994') and
ar_Wettkampf.`Wettkampfdatum` LIKE '%2013%'
Group By
AthletenID
Order by
DiszOrder Desc
Limit
0, 100
You can have a subquery which separately gets the lowest DiszOrder for each AthletenID and join it with the other table so you can freely get the other value of the columns.
SELECT a.AthletenID,
a.Leistung,
a.Disziplin,
ar_Leistungen.Klasse,
a.DiszOrder),
b.Vorname,
b.Jahrgang,
c.Wettkampfdatum
FROM ar_Leistungen a
INNER JOIN ar_Athleten b
ON b.ID = a.AthletenID
INNER JOIN ar_Wettkampf c
ON a.WettkampfID = c.ID
INNER JOIN
(
SELECT AthletenID, MIN(DiszOrder) DiszOrder
FROM ar_Leistungen
GROUP BY AthletenID
) d ON a.AthletenID = d.AthletenID AND
a.DiszOrder = d.DiszOrder
WHERE a.Disziplin = '100' AND
a.Leistung > 0 AND
(b.Jahrgang IN ('1995', '1994'))

MySQL limit inside of the subquery produces error

I'm receiving:
[Err] 1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
While executing the following query:
UPDATE account.account
SET STATUS = 'BLOCK'
WHERE
id IN (
SELECT
p.account_id
FROM
log.log
LEFT JOIN player.player p ON (p.id = log.who)
WHERE
vnum = 71054
AND how = 'BUY'
GROUP BY
log.`who`
HAVING
COUNT(log.who) > 2
LIMIT 10
);
Is there a posibility to rewrite this query so MySQL could execute it?
The solution is to join against a subquery rather than use an IN(). The INNER JOIN will only return rows in account matching ids from the limited subquery. It is then possible to do the UPDATE without a WHERE clause.
Update
account.account AS account
INNER JOIN (
SELECT
p.account_id
FROM
log.log
LEFT JOIN player.player p ON (p.id = log.who)
WHERE
vnum = 71054
AND how = 'BUY'
GROUP BY log.`who`
HAVING COUNT(log.who) > 2
LIMIT 10
) subq ON account.id = subq.id
SET STATUS='BLOCK'
To verify the rows that would be modified, use a SELECT first:
SELECT
account.*
FROM
account.account
INNER JOIN (
SELECT
p.account_id
FROM
log.log
LEFT JOIN player.player p ON (p.id = log.who)
WHERE
vnum = 71054
AND how = 'BUY'
GROUP BY log.`who`
HAVING COUNT(log.who) > 2
LIMIT 10
) subq ON account.id = subq.id