LIMIT中的MYSQL子查询

时间:2016-12-10 14:01:59

标签: mysql sql subquery limit

我想知道是否可以在LIMIT中使用子查询。

我之所以要使用它,是为了回报20%(1/5)的最佳购买客户。

例如(虽然这显然不起作用):

SELECT id, revenue
FROM customers
ORDER BY revenue DESC
LIMIT (SELECT (COUNT(*) / 5) FROM customer) 

有没有办法让子查询达到限制,或者以不同的方式返回20%?

1 个答案:

答案 0 :(得分:0)

使用ANSI SQL执行此操作的典型方法是使用窗口函数:

SELECT id, revenue
FROM (SELECT c.*,
             ROW_NUMBER() OVER (ORDER BY revenue DESC) as seqnum,
             COUNT(*) OVER () as cnt
      FROM customers
     ) c
WHERE seqnum <= cnt * 0.2
ORDER BY revenue DESC;

大多数数据库都支持这些功能。

MySQL是少数几个不支持窗口功能的数据库之一。您可以使用变量:

SELECT id, revenue
FROM (SELECT c.*, (@rn := @rn + 1) as rn
      FROM customers c CROSS JOIN
           (SELECT @rn := 0) params
      ORDER BY c.revenue DESC
     ) c
WHERE rn <= @rn / 5;  -- The subquery runs first so @rn should have the total count here.