有没有办法根据 mySQL 中另一个查询的结果来限制查询?

Is there a way to limit a query based on the result of another in mySQL?

所以我有一个正在使用的查询,但我想在我的第二个查询的限制中使用第一个查询的计数,这可能吗?例如

 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'

所以我在第一个查询中得到了一个数字,我想像这样使用它。

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

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.

所以你不能使用表达式或子查询或类似的东西。

您可以 运行 您的第一个查询,将结果提取到一个变量中,然后在第二个查询中使用该变量。

你可以把它变成一个变量,然后在第二段代码中使用它:

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')

注:称其为@number_required而不是number_required