Mysql INNER JOIN疑惑

时间:2013-07-10 11:48:49

标签: mysql sql inner-join

我的查询如下:

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_pos)(order_main),从他们需要找到关系(order_product)然后我才能找到我的产品时间(产品) )。但是对于每个订单,产品的位置可能是几个。我需要找到MAX产品时间。

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

我认为这个SQL查询非常复杂。看来我可以更容易地做到这一点吗?

由于

1 个答案:

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