MySQL subquery to get a list of IDs from one table to query a second table

瘦欲@ 提交于 2019-12-25 06:41:08

问题


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:


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 
    ...


来源:https://stackoverflow.com/questions/10433233/mysql-subquery-to-get-a-list-of-ids-from-one-table-to-query-a-second-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!