1

我有一个 mysql 查询类型

select some_value FROM table WHERE (subquery) IN ( values )

这似乎非常慢!

我有一个带有订单的 mysql 表和第二个带有相应处理状态的表。我现在想显示所有具有最后状态代码 = 1 的订单。

表顺序(id = 主键)

id | value
---+-------
1  +  10
2  +  12
3  +  14

表状态(id = 主键)

id | orderid | code
---+---------+-------
1  +  1      +  1
2  +  2      +  1
3  +  2      +  2
4  +  1      +  3
5  +  3      +  1

我的查询是:

select order.id FROM order WHERE
( select state.code FROM state WHERE state.orderid = order.id ORDER BY state.id DESC LIMIT 0,1 )     IN ( '1' )

处理一个订单大约需要 15 秒。如何修改 mysql 语句以加快查询处理时间?

4

2 回答 2

1

更新

试试这个:

select s1.orderid
from state s1
left outer join state s2 on s1.orderid = s2.orderid
    and s2.id > s1.id
where s1.code = 1
    and s2.id is null

您可能需要在state.orderid.

SQL 小提琴示例

CREATE TABLE state
    (`id` int, `orderid` int, `code` int)
;

INSERT INTO state
    (`id`, `orderid`, `code`)
VALUES
    (1, 1, 1),
    (2, 2, 1),
    (3, 2, 2),
    (4, 1, 3),
    (5, 3, 1)
;

查询

select s1.orderid
from state s1
left outer join state s2 on s1.orderid = s2.orderid
    and s2.id > s1.id
where s1.code = 1
    and s2.id is null

结果

| ORDERID |
|---------|
|       3 |
于 2013-10-19T15:22:31.133 回答
1

在这种情况下,我认为您可以简单地忘记order,因为所有信息都保留在其中state

SELECT x.id, x.orderid
FROM state AS x
WHERE x.code =1
AND x.id = (
SELECT max( id )
FROM a
WHERE orderid = x.orderid ) 

也许也可以CRUD通过将最后一个状态直接放入order表中来更改您的状态,这会更好

于 2013-10-19T17:08:14.540 回答