-1

我的查询如下:

SELECT * FROM order_main t
  LEFT JOIN order_pos op ON t.id=op.order_main_id
  LEFT JOIN order_product oprod ON op.id=oprod.order_pos_id
  LEFT JOIN product pr ON pr.id=oprod.product_id
  INNER JOIN(
              SELECT t.id, MAX(pr.hours) as HoursMax FROM order_main t
                LEFT JOIN order_pos op ON t.id=op.order_main_id
                LEFT JOIN order_product oprod ON op.id=oprod.order_pos_id
                LEFT JOIN product pr ON pr.id=oprod.product_id
              WHERE (t.created <= '2013-07-01' AND t.status >= 1 AND t.status < 3 AND pr.hours IS NOT NULL)
                    OR (t.created > '2013-07-01' AND t.payed = 1 AND t.report_sended = 0 AND pr.hours IS NOT NULL) GROUP BY t.id
            ) grouptt ON t.id = grouptt.id
WHERE (t.created <= '2013-07-01' AND t.status >= 1 AND t.status < 3 AND pr.hours IS NOT NULL AND DATE_SUB(NOW(), INTERVAL grouptt.HoursMax HOUR) > t.created)
      OR (t.created > '2013-07-01' AND t.payed = 1 AND t.report_sended = 0 AND pr.hours IS NOT NULL AND DATE_SUB(NOW(), INTERVAL grouptt.HoursMax HOUR) > t.created)

有没有 INNER JOIN 的办法?

更新:

我正在尝试选择所有迟到的订单。

我的表产品中有几个小时,您可以看到我需要找到订单(order_main)的所有位置(order_pos),并且我需要从中找到关系(order_product),然后我才能找到我的产品时间(产品)。但是每个订单的产品位置可能有几个。我需要找到 MAX 产品时间。

当我从每个订单中找到 MAX 产品小时数时(现在我使用 INNER JOIN 进行),我可以将其与订单创建日期(t.created)进行比较。

我认为这个sql查询非常复杂。看来我可以更轻松地做到这一点?

谢谢

4

1 回答 1

0

由于您只需要 order_main 中的字段,因此您至少可以摆脱外部查询中的连接和条件(并且使用内部连接):

SELECT * FROM order_main om
INNER JOIN
    (SELECT t.id, t.created
     FROM order_main t
     INNER JOIN order_pos op ON t.id = op.order_main_id
     INNER JOIN order_product oprod ON op.id = oprod.order_pos_id
     INNER JOIN product pr ON pr.id = oprod.product_id
     WHERE (t.created <= '2013-07-01' AND t.status IN (1,2))
     OR (t.created > '2013-07-01' AND t.payed = 1 AND t.report_sended = 0)
     GROUP BY t.id
     HAVING DATE_ADD(t.created, INTERVAL MAX(pr.hours) HOUR) < NOW()) AS grouptt
ON om.id = grouptt.id
于 2013-07-12T08:29:39.673 回答