我正在尝试从MySQL(版本:5.6.29和10.1.28-MariaDB)获得前n行(目前为2行)。
我在SO或其他地方(example1example2)上看到了简单的示例
问题是我的查询更加复杂,而且似乎无法正常运行。

我在图表上看到了表格(为简洁起见,删除了一些字段):

mysql - MySQL选择每组嵌套的前n条记录-LMLPHP

每个Purchase_item可以是coupon,purchase_offer或subscription_plan(一个有效,而另外两个为null)。这些每个都有subscription_days > 0

最内层的SELECT本身可以正常工作。第二个SELECT不能按预期工作(即使我删除了外部选择),对于同一purchase_rankcustomer_uuid通常是相同的,就像最里面的选择没有按customer_uuid排序一样。

有任何想法吗?我read ORDER BY在嵌套查询中不能很好地工作,也许这就是我的问题?那我该怎么做呢?
还是查询优化器正在做一些奇怪的事情?我尝试用IF替换CASE,结果相同。
这是代码:

SELECT
    id,
    uuid,
    purchase_offer,
    subscription_plan,
    coupon,
    customer_uuid,
    payment_date,
    subscription_days,
FROM
    (SELECT
        id,
            uuid,
            purchase_offer,
            subscription_plan,
            coupon,
            customer_uuid,
            payment_date,
            subscription_days,
            @purchase_rank := CASE @current_customer
                WHEN customer_uuid THEN @purchase_rank + 1
                ELSE 1
            END AS purchase_rank,
            @current_customer:= customer_uuid AS current_customer
    FROM
        (SELECT
            pi.id,
            pi.uuid,
            pi.purchase_offer,
            pi.subscription_plan,
            pi.coupon,
            pi.customer_uuid,
            p.payment_date,
            IFNULL(po.subscription_days, IFNULL(sp.subscription_days, cpo.subscription_days)) AS subscription_days
    FROM
        purchase_item pi
    JOIN purchase p ON p.id = pi.purchase
    LEFT JOIN purchase_offer po ON pi.purchase_offer = po.id
    LEFT JOIN subscription_plan sp ON pi.subscription_plan = sp.id
    LEFT JOIN coupon cp ON pi.coupon = cp.id
    LEFT JOIN purchase_offer cpo ON cp.purchase_offer = cpo.id
    WHERE
        p.status = 'COMPLETED'
            AND pi.customer_uuid IS NOT NULL
            AND p.payment_date IS NOT NULL
            AND (po.subscription_days > 0
            OR sp.subscription_days > 0
            OR cpo.subscription_days > 0)
    ORDER BY pi.customer_uuid , p.payment_date DESC) AS temp)
AS pu
WHERE
    pu.purchase_rank <= 2
ORDER BY pu.customer_uuid , pu.payment_date DESC


任何帮助将不胜感激。提前致谢。

最佳答案

对于MySql查询的这种限制,您只需在语句末尾添加LIMIT 0, 2

有关限制声明的详细信息,请随时检查this documentation with realtime example.



编辑我

例如:从一条语句获取前n个结果:

SELECT * FROM purchase
ORDER BY payment_date ASC
LIMIT n


反过来:

SELECT * FROM purchase
ORDER BY payment_date DESC
LIMIT n


如果您知道要跳过查询的前n个结果,则可以从给定的偏移量开始LIMIT。例如,我们要跳过前10个结果:

SELECT * FROM purchase
ORDER BY payment_date DESC
LIMIT 10, n

10-06 06:40