0

我需要使用过滤器和排序来获取 2 个表的记录。表:ra_pedidos、ra_pedido_has_pedido_status

它在 MySQL5.0 中完美运行,但现在在 5.5 中它不再带来正确的结果。

我需要在同一行中显示每个请求的第一个状态和最后一个状态更改的日期,并忽略已取消的请求。

搜索示例(ra_pedido_has_pedido_status):

SELECT id_pedido, id_pedido_status, data
    FROM ra_pedido_has_pedido_status
    WHERE id_pedido IN (86291, 86745, 86622);

结果:

+-----------+------------------+---------------------+
| id_pedido | id_pedido_status | data                |
+-----------+------------------+---------------------+
|     86291 |                1 | 2017-10-30 11:16:12 |
|     86291 |                2 | 2017-10-30 14:14:53 |
|     86291 |                3 | 2017-10-31 08:18:47 |
|     86291 |               11 | 2017-11-07 12:08:04 |
|     86622 |                1 | 2017-11-04 12:23:21 |
|     86622 |                2 | 2017-11-04 12:47:33 |
|     86622 |                3 | 2017-11-06 08:24:20 |
|     86622 |               90 | 2017-11-07 08:40:55 |
|     86745 |                1 | 2017-11-07 10:59:51 |
|     86745 |                2 | 2017-11-07 11:09:46 |
+-----------+------------------+---------------------+

现在报告 SQL:
[编辑] 解释:JOIN获取第一个匹配行,然后ORDER BYSELECT此联接力中获取最后一行。请注意,id_pedido86622 不应列出,因为它已被取消(最后一个id_pedido_status= 90),并且已在HAVING

SELECT  o.id_pedido AS id, pus.id_pedido_status, pus.data
    FROM  ra_pedido AS o
    INNER JOIN  
    (
        SELECT  ra_pedido_has_pedido_status.*
            FROM  ra_pedido_has_pedido_status
            ORDER BY  data DESC
    ) AS pus  ON o.id_pedido = pus.id_pedido
    WHERE  o.id_pedido IN (86291, 86745, 86622)
    GROUP BY  o.id_pedido
    HAVING  id_pedido_status < 90
    ORDER BY  data DESC;

这是使用 MySQL 5.0 的结果,预期:

+-------+------------------+---------------------+
| id    | id_pedido_status | data                |
+-------+------------------+---------------------+
| 86291 |               11 | 2017-11-07 12:08:04 |
| 86745 |                2 | 2017-11-07 11:09:46 |
+-------+------------------+---------------------+

这是使用 MySQL 5.5 的结果,出乎意料:

+-------+------------------+---------------------+
| id    | id_pedido_status | data                |
+-------+------------------+---------------------+
| 86745 |                1 | 2017-11-07 10:59:51 |
| 86622 |                1 | 2017-11-04 12:23:21 |
| 86291 |                1 | 2017-10-30 11:16:12 |
+-------+------------------+---------------------+

我需要在 SQL 中更改什么?
谢谢和对不起我的英语...

4

0 回答 0