'Is there a way to limit a query based on the result of another in mySQL?
So I have a query that I'm using but I want to use the count of the first query in my limit of my 2nd query, is that possible? For example
SELECT
Round(0.07 * Count(*), 0) AS number_required
FROM trinkets t
LEFT JOIN orders o
ON p.order_id = o.id
WHERE o.trinket_id IN ( 27 )
AND t.valid_from >= '2022-01-01'
AND t.valid_from <= '2022-01-31'
So I get a number in this first query and I want to use it like this.
SELECT
Rand() AS 'random',
t.order_id,
t.serial_number,
t.valid_from,
t.valid_till AS 'valid_to',
comp.org_name AS 'subject_org',
FROM
trinkets t
LEFT JOIN orders o ON t.order_id = o.id
LEFT JOIN companies comp ON o.company_id = comp.id
WHERE
t.valid_from >= '2022-01-01'
AND (
o.status = 3
AND o.reason IN (6, 11)
)
AND o.trinket_id = 27
ORDER BY
random ASC
limit number_required
Solution 1:[1]
https://dev.mysql.com/doc/refman/8.0/en/select.html
- Within prepared statements, LIMIT parameters can be specified using ? placeholder markers.
- Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables.
So you can't use expressions or subqueries or anything like that.
You could run your first query, fetch the result into a variable, and then use that variable in the second query.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bill Karwin |
