mysql子查询引用外表

时间:2018-05-07 19:24:13

标签: mysql sql subquery

我试图在子查询选择中使用外表。虽然我可以硬编码值并获得所需的结果;我真的需要使用外部的phppos_items表;但无法弄清楚。以下是简化查询。有没有办法做到这一点?我使用子查询的原因是因为我想在连接中只获得一行。

我尝试获取外围表的部分是 XXX

SELECT SUM(trans_current_quantity) as quantity FROM `phppos_items` 
LEFT JOIN `phppos_location_items` ON `phppos_location_items`.`item_id` = `phppos_items`.`item_id` and `phppos_location_items`.`location_id` IN(1)
LEFT JOIN 
(SELECT * FROM phppos_inventory WHERE trans_date < '2018-05-06 23:59:59' and
trans_items = *XXX* ORDER BY trans_date DESC LIMIT 1) as inventory 
ON `phppos_location_items`.`item_id` = `inventory`.`trans_items`

2 个答案:

答案 0 :(得分:2)

这是您的查询,表别名使其更具可读性:

SELECT SUM(trans_current_quantity) as quantity
FROM phppos_items i LEFT JOIN
     phppos_location_items li
     ON li.item_id = i.item_id and li.location_id IN (1) LEFT JOIN 
     (SELECT * 
      FROM phppos_inventory inv
      WHERE inv.trans_date < '2018-05-06 23:59:59' and
            trans_items = *XXX*
      ORDER BY trans_date DESC LIMIT 1
     ) inv 
    ON li.item_id = inv.trans_items;

我只能将trans_current_quantity解释为来自phppos_inventory。在您编写查询时,LEFT JOIN似乎是多余的。

你真正想要的是横向连接。这在MySQL中不起作用,唉。这是下一个最接近的事情:

SELECT SUM(inv.trans_current_quantity) as quantity
FROM phppos_items i JOIN
     phppos_location_items li
     ON li.item_id = i.item_id and li.location_id IN (1) JOIN 
     phppos_inventory inv
     ON li.item_id = inv.trans_items
WHERE li.item_id = XXX AND
      inv.trans_date = (SELECT MAX(inv2.trans_date)
                        FROM phppos_inventory inv2
                        WHERE inv2.trans_date < '2018-05-07' and
                              inv2.trans_items = li.item_id
                       );

我还通过添加秒来修正日期比较。如果这不对,你可以修复它,但查询更具可读性。

答案 1 :(得分:-1)

假设您要将 XXX 替换为主键到phppos_items(即item_id),您可能只需要在外部查询中对表进行别名,并通过子查询中的别名引用它。如果trans_items引用的不是主键(或者如果item_id)不是主键,那么我需要更多信息来帮助......

SELECT SUM(trans_current_quantity) as quantity FROM `phppos_items` AS items1
LEFT JOIN `phppos_location_items` ON `phppos_location_items`.`item_id` = `phppos_items`.`item_id` and `phppos_location_items`.`location_id` IN(1)
LEFT JOIN 
    (SELECT * FROM phppos_inventory WHERE trans_date < '2018-05-06 23:59:59' and trans_items = items1.item_id ORDER BY trans_date DESC LIMIT 1) as inventory 
     ON `phppos_location_items`.`item_id` = `inventory`.`trans_items`