MySQL subquery to get a list of IDs from one table

2019-09-10 20:14发布

I have two tables, one is products and one salesRecords

I am using this query:

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

The products table contains all I need to know about a product, and salesRecords contains details such as the saleDate, quantity sold, discounts given etc, so what I am trying to achieve here is a list of sales for all products with the brand id 100 by month and year from a Unix Time field called "saleDate"

It works, but is very slow.

Can anyone advise a faster way of doing this?

If I manually plug the list of IDs into the query it seems to work faster, so should I run two queries?

1条回答
贼婆χ
2楼-- · 2019-09-10 20:43

I have rewrote your query with a single inner join. Try it and come back with news:

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

Also, to avoid where clause, you can put restrinction in on operation:

    ...
    SUM(quantity) as qty 
 FROM salesRecords s inner join 
      products on p.brand =100 and s.itemNo = p.id 
 GROUP BY 
    ...
查看更多
登录 后发表回答