【问题标题】:Using LIMIT to get AVG from 2 tables使用 LIMIT 从 2 个表中获取 AVG
【发布时间】:2014-07-10 16:41:03
【问题描述】:

我目前有一个从receive_pallet 表中获取每个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;

我在尝试测试时收到此错误。 [Err] 1235 - 此版本的 MySQL 尚不支持 'LIMIT & IN/ALL/ANY/SOME 子查询'

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

【问题讨论】:

  • 字段date_entereddate_ordered属于哪个表?
  • 看第一段代码上面的注释。(date_entered from the table receive_pallet and date_ordered from the table cs_po)
  • 抱歉,错过了。正在努力...

标签: mysql limit


【解决方案1】:

看看这个:

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
;

我把它简化了一点,但我认为它可以按照你想要的方式工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多