0

我有两张桌子,一张是products一张salesRecords

我正在使用这个查询:

SELECT 
    DAY(FROM_UNIXTIME(saleDate)) as day,
    MONTH(FROM_UNIXTIME(saleDate)) as mnth,
    YEAR(FROM_UNIXTIME(saleDate)) as yr,   
    COUNT(id) as invCount, SUM(quantity) as qty 
 FROM salesRecords WHERE itemNo IN 
      (SELECT GROUP_CONCAT(convert(id, CHAR(8))) as ids FROM products WHERE brand =100 GROUP by brand) 
    GROUP BY 
       mnth, yr 
    ORDER BY saleDate

products 表包含我需要了解的有关产品的所有信息,而 salesRecords 包含诸如 saleDate、已售数量、给予的折扣等详细信息,所以我在这里尝试实现的是所有具有品牌 ID100的产品的销售列表来自名为“saleDate”的 Unix 时间字段的月份和年份

它可以工作,但速度很慢。

任何人都可以建议一种更快的方法吗?

如果我手动将 ID 列表插入到查询中,它似乎工作得更快,那么我应该运行两个查询吗?

4

1 回答 1

1

我已经用一个内部联接重写了您的查询。试试看,然后回来新闻:

SELECT 
    DAY(FROM_UNIXTIME(saleDate)) as day,
    MONTH(FROM_UNIXTIME(saleDate)) as mnth,
    YEAR(FROM_UNIXTIME(saleDate)) as yr,   
    COUNT(id) as invCount, 
    SUM(quantity) as qty 
 FROM salesRecords s inner join 
      products on s.itemNo = p.id 
 WHERE 
      p.brand =100
 GROUP BY 
       `day`, mnth, yr 
 ORDER BY 
       saleDate

此外,为了避免 where 子句,您可以在on操作中使用限制:

    ...
    SUM(quantity) as qty 
 FROM salesRecords s inner join 
      products on p.brand =100 and s.itemNo = p.id 
 GROUP BY 
    ...
于 2012-05-03T14:19:04.570 回答