Search code examples
mysqlsqlsubquerylimit

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

  • You can make it a variable and use it in the second piece of code:

    SET @number_required = (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')
    

    Note: Call it as @number_required not number_required