简体   繁体   中英

sql query chokes the server

When I run this query mysql server cpu usages stays at 100% and chokes the server. What am I doing wrong?

SELECT * 
FROM projects p, orders o, invoices i
WHERE p.project_state =  'product'
AND (
p.status =  'expired'
OR p.status =  'finished'
OR p.status =  'open'
)
AND p.user_id =  '12'
AND i.projectid =0
GROUP BY i.invoiceid
LIMIT 0 , 30

You are including the orders table but not joining to it. This will make a full cross join that can potentially produce millions of rows.

Use EXPLAIN to find out the query plan. From that you can work out what indexes will be required. Those indexes will vastly improve performance.

Also you are not limiting the orders in any way.

You didn't put any joins on the tables. I believe by default that will do a cross join. That means if you have 1000 projects, 100,000 orders and 100,000 invoices the resultset will be 1,000,000,000,000 (1 trillion) records.

You probably want to put some inner joins between those tables.

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