开发者

sql query chokes the server

When I run this query mysql server cpu usages 开发者_StackOverflow社区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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜