MySQL选择还是选择?

MySQL选择还是选择?,sql,mysql,Sql,Mysql,我在sql查询中遇到问题,以下是我尝试执行的操作的概括: select oh.a as a, oh.b as b, oi.c as c, (select h.d from history h where h.id = oh.id and h.d not in ('d1', 'd2') order by h.date limit 1) as d from order_header oh join order_item oi on oh.order_id = oi.order_id wh

我在sql查询中遇到问题,以下是我尝试执行的操作的概括:

select 
oh.a  as a, 
oh.b  as b, 
oi.c  as c,
(select h.d from history h where h.id = oh.id and h.d not in ('d1', 'd2') order by h.date limit 1) as d
from order_header oh
join order_item oi on oh.order_id = oi.order_id
where oh.state in (0, 10, 20)
我的问题是,这种类型的查询在MySQL 5.0.77版中运行良好,但在MySQL 5.1.47版中失败。我所说的问题是,当查询运行MySQL时,CPU将保持在100%,并且永远不会完成。即使在select前面加上explain,查询也不会返回

如有任何建议或建议,将不胜感激

谢谢,
Doug

以下是我将如何编写此查询:

select 
oh.a  as a, 
oh.b  as b, 
oi.c  as c,
h1.d as d
from order_header oh
join order_item oi on oh.order_id = oi.order_id
left outer join history h
 on h.id = oh.id and h.d not in ('d1', 'd2')
left outer join history h2
 on h2.id = oh.id and h2.d not in ('d1', 'd2') 
 and (h.date > h2.date or h.date = h2.date and h.id > h2.id) 
where oh.state in (0, 10, 20) and h2.id is null

我发现它和解释一样有用。您可以在运行查询之前启用它,然后转储每个步骤的计时。这是一种非常方便的优化子查询的方法——您可能会注意到,当子查询可以作为WHERE子句执行一次时,它会对SELECT子句中的每一行执行。

您给出它多长时间了?除了你的版本,还有什么其他的改变吗?尺寸?数据?谢谢杰夫,这很方便。解释这件事很好,但它只会让你“知道”事情需要多长时间。我要试试这个!比尔,谢谢你的反馈,我会采纳你的建议,调整我的实际查询,并用它做一些测试。再次感谢!