MySQL子查询从一个表中获取ID列表以查询第二个表

时间:2012-05-03 14:14:28

标签: mysql subquery

我有两个表,一个是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

产品表包含我需要知道的关于产品的所有内容,而salesRecords包含详细信息,例如saleDate,销售数量,给出的折扣等,所以我想在这里实现的是所有产品的销售清单。来自名为“saleDate”的Unix时间字段的月份和年份的品牌ID 100

它有效,但速度很慢。

任何人都可以建议更快的方式吗?

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

1 个答案:

答案 0 :(得分:0)

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

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操作中添加restrinction:

    ...
    SUM(quantity) as qty 
 FROM salesRecords s inner join 
      products on p.brand =100 and s.itemNo = p.id 
 GROUP BY 
    ...