0

我面临一个 mySQL 问题:我有一个包含这些列的 mySQL 表,它存储每个订单和订单的每个状态:

    id_order_history / id_employee / id_order / id_order_state / date_add 

我想得到一个 *id_order* 的列表,它们在特定的 *id_order_state* 中 - 比如说 10 - 但我不想获得在这个特定状态之后状态发生变化的订单,也不想收集不到 7 天的订单...

以下是我如何做到这一点:

首先查询以获取订单和日期列表:

SELECT id_order, date
           FROM '._DB_PREFIX_.'ps_order_history, 
           WHERE TO_DAYS(NOW()) - TO_DAYS(date_add) <= 7 
           AND id_order_state = 10

然后一个循环只获取没有最新状态的订单:

$query = '   SELECT id_order, date
           FROM '._DB_PREFIX_.'ps_order_history, 
           WHERE ';

foreach ( $listAbove, $item) {
     $query =+ '
                (( date > $item['date'])
                AND ( id_order = $item['id']))
             ';
 }
 $orderlist = Db::getInstance()->ExecuteS($query);

这并不是真正的优化,我很确定我可以只用一个查询来做到这一点,但我真的不知道怎么做。

你知道如何使这个更清洁吗?

4

2 回答 2

2

如果我理解这一点,例如,您只需要最近状态等于 10 的订单。因此,让我们从获取订单和最新状态开始

SELECT
   id_order,
   MAX(id_order_history) as m
FROM ps_order_history
GROUP BY id_order

这为我们提供了每个订单的最新订单历史项目(假设id_order_history是 PK 并且最大值表示最近的订单条目)。现在我们只需搜索该子查询以找到我们想要的条件。

SELECT
   poh.id_order
FROM ps_order_history poh
INNER JOIN
 (SELECT
   id_order,
   MAX(id_order_history) as m
 FROM ps_order_history
 GROUP BY id_order) sub
 ON sub.id_order = poh.id_order
   AND sub.m = poh.id_order_history
WHERE poh.id_order_state = 10
   AND TO_DAYS(NOW()) - TO_DAYS(poh.date_add) <= 7
于 2013-01-11T16:39:05.213 回答
0

WHERE您可以在子句中使用子查询。这是一个例子:

create table order_history 
(orderid int, orderstate int, orderdate date, 
primary key(orderid, orderstate, orderdate));

insert into order_history values (1,1,makedate(2012,1));
insert into order_history values (1,2,makedate(2012,2));
insert into order_history values (1,3,makedate(2012,3));
insert into order_history values (2,1,makedate(2012,1));
insert into order_history values (2,3,makedate(2012,3));
insert into order_history values (3,1,makedate(2012,1));

此查询现在将选择最新orderstate为 3 的所有项目:

select a.orderid, a.orderdate from order_history a
where a.orderdate = 
  (select max(orderdate) from order_history b where b.orderid = a.orderid)
and a.orderstate=3

要按 orderdate 进行限制,只需在外部where子句中添加另一个子句以供您选择日期。

于 2013-01-11T16:51:01.317 回答