mysql选择Where(子查询)IN

时间:2013-10-19 15:18:46

标签: php mysql

我有一个类型为

的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语句以加快查询处理时间?

2 个答案:

答案 0 :(得分: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 Fiddle Example

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 |

答案 1 :(得分: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,这样会更好