简体   繁体   中英

Slow MySQL left join query

I have the following 3 MySQL tables (shown as table_name:column_list):

tbl_product: id, name
tbl_sales: productid, date
tbl_impressions: productid, date

tbl_products stores available products, tbl_sales stores each sale of a product and tbl_impressions stores each impression of a product. I would like to find products that have been sold, displayed, or both . My attempted query for this is:

SELECT prod.name
FROM tbl_product prod
LEFT JOIN tbl_sales sales ON sales.productid=prod.id
LEFT JOIN tbl_impressions imp ON imp.productid=prod.id
WHERE (sales.productid IS NOT NULL) OR (imp.productid IS NOT NULL)

However, in my tests this query is extremely slow. What options do I have for improving it?

Use Index on productid and id fields in all these table. The JOIN will give performance if we have index on joining fields.

SELECT name FROM tbl_product INNER JOIN tbl_sales ON id = productid
UNION
SELECT name FROM tbl_product INNER JOIN tbl_impressions ON id = productid

Using EXISTS instead of your LEFT JOIN s should help.

SELECT prod.name
FROM tbl_product prod
WHERE EXISTS ( SELECT 1 FROM tbl_sales sales WHERE sales.productid = prod.id )
   OR EXISTS ( SELECT 1 FROM tbl_impressions imp WHERE imp.productid = prod.id )

Make sure to add indexes on tbl_sales.productid and tbl_impressions.productid . (as others said)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM