使用LIMIT从2个表中获取AVERAGE

时间:2014-07-10 16:41:04

标签: mysql limit

我目前有一个查询从receive_pallet TABLE获取每个product_id。除了每个id之外,它还获得了在订购/接收日期之间的日期的AVG(来自TABLE receive_pallet的date_entered和来自TABLE cs_po的date_ordered)

 SELECT a.product_id, avg(a.date) AS AVG
 FROM (SELECT DATEDIFF(date_entered,date_ordered) AS date,po_number_full, product_id
             FROM cs_po,receive_pallet
             WHERE cs_po.id = receive_pallet.po_number_full
             ORDER BY cs_po.id DESC )a 
 GROUP BY a.product_id;

结果如下:

 product_id     AVG
 00010005.01S   25.2500
 00010005.04D   19.0000
 00010010.01S   21.2680
 00010020.02S   15.1250
 00010040.04S   12.2400
 00010080.20S   16.6667

此查询有效,但我想将其限制为AVG最后5次发货,而不是所有发货。这是我这样做的查询,

 SELECT a.product_id, avg(a.date) AS AVG
 FROM (SELECT DATEDIFF(date_entered,date_ordered) AS date,po_number_full, product_id
                                FROM cs_po,receive_pallet
                                WHERE cs_po.id = receive_pallet.po_number_full
                                AND product_id IN (SELECT product_id , date_entered,    date_ordered FROM receive_pallet LIMIT 0,5)
                                ORDER BY cs_po.id DESC
                                )a 
  GROUP BY a.product_id;

我尝试测试时出现此错误。 [错] 1235 - 这个版本的MySQL还没有支持' LIMIT& IN / ALL / ANY / SOME子查询'

我知道我需要用INNER JOIN替换IN()子句,因为在IN()子查询中根本不支持LIMIT但是如果我有两个,我不知道从哪里开始子查询/添加连接的位置。感谢。

1 个答案:

答案 0 :(得分:0)

看看这个:

SELECT 
    a.product_id, 
    AVG(a.date) AS AVG
FROM (
        SELECT 
            DATEDIFF(date_entered, date_ordered) AS date,
            product_id
        FROM 
            cs_po c
                JOIN (
                    SELECT 
                        date_entered,
                        product_id,
                        po_number_full
                    FROM 
                        receive_pallet 
                    ORDER BY
                        date_entered DESC
                    LIMIT 5
                ) r ON c.id = r.po_number_full
        ORDER BY 
            c.id DESC
        ) a 
GROUP BY 
    a.product_id
;

我简化了一下,但我认为它的工作方式与你想要的一样。