MySQL查询导致服务器崩溃?
在我的 MySQL 数据库中,我有两个表:“orders”和“orders_lines”。订单包含有关客户、订单日期等的信息。 Orders_lines 包含有关订购产品的数据,例如product_id、价格、数量、税率等。
我目前正在构建一个搜索页面,我想在其中返回包含特定产品的订单。例如,我想返回product_id为2的所有订单。我想到了这样的查询:
SELECT * FROMordersWHEREorder_idIN(SELECTorder_idFROMorders_linesWHEREproduct_id=2)
但是当我执行时今天早上的查询我不得不打电话给托管提供商来终止 MySQL 进程,因为它太重了。从来没有听说过,也不知道为什么,现在我非常绝望。 orders 表包含大约 30.000 行,orders_lines 表大约包含 38.000 行。
欢迎就我的数据库崩溃的原因、如何更改查询以使其正常工作或如何实现显示包含特定产品的订单的目标提出任何建议!
亲切的问候,
马丁
In my MySQL database I have two tables: 'orders' and 'orders_lines'. Orders contains info about the customer, order date, and so on. Orders_lines contains data about the oredered products, like product_id, price, quantity, tax rate, and so on.
I'm currently building a search-page in which I'd like to return the orders that contain a specific product. For example, I'd like to return all orders with product_id 2. I thought of a query like:
SELECT * FROM orders WHERE order_id IN ( SELECT order_id FROM orders_lines WHERE product_id = 2 )
But when I executed the query this morning I had to call the hosting provider to terminate the MySQL processes because it was way to heavy. Never heard of it and could not figure out why, and I'm pretty desperate at the moment. The orders table contains about 30.000 rows, the orders_lines table about 38.000 rows.
Any suggestions why my database crashes, how to change the query to make it work correctly or how to achieve my goal of displaying orders that contain a certain product are welcome!
Kind regards,
Martijn
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以使用
JOIN
(和GROUP BY
)重写查询:或者最好 - 因为您只需要来自
orders
表的结果 - 使用EXISTS
:但是在再次运行可能导致服务器故障的操作之前请检查您的索引和
EXPLAIN
。The query can be rewritten with
JOIN
(andGROUP BY
):or preferably - as you want only results from the
orders
table - withEXISTS
:But check your indexes and the
EXPLAIN
before running again something that might cause your server to fault.我不确定这是否是您所需要的,无论如何尝试:
I'm not sure this is what you need, anyway try:
据我所知,在这种情况下,内部联接(又名自然联接)是最好的方法。 “WHERE .. IN ..”往往是一项昂贵的操作。
As far as I know is an inner join (aka naturual join) the best way to go in such cases. 'WHERE .. IN .. tends to be an expensive operation.