问题
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