Mysql多连接查询问题

时间:2018-04-19 08:16:48

标签: php mysql laravel

我有三张桌子要加入,请看这三张桌子

composite_inventories enter image description here

composite_has_inventories enter image description here

库存 enter image description here

以上三个表我使用以下查询加入

SELECT u.id, u.purchase_item_name,u.sales_item_name, us.type ,Group_concat(s.itemcode) as Items FROM composite_inventories as u LEFT JOIN composite_has_inventories as us ON u.id = us.composite_inventory_id LEFT JOIN inventories as s ON US.inventory_id = s.id GROUP BY us.composite_inventory_id,us.type

我输出了上面的查询,如下所示

enter image description here

但不是上面的输出我需要输出应该像这样

 id | Purchase_item_name | sales_item_name | purchase_items   | sales_items
  -------------+-------+-----------+----------------------------
   12  | golden          | NULL             | A123,Z523,QQ5252 | NULL
   13  | test            | demoabc          | Z523,QQ5252      | Z523

请帮我将此查询转换为laravel查询。

1 个答案:

答案 0 :(得分:0)

要实现您想要的目标,必须两次加入库存表,一次购买,一次购买。然后,您可以对每个GROUP_CONCAT ed表中的项目执行JOIN,以获得purchase_itemssales_items

此查询应该为您提供所需的结果(SQLFiddle

SELECT u.id, u.purchase_item_name,u.sales_item_name, us.type,
GROUP_CONCAT(p.itemcode) AS purchase_items,
GROUP_CONCAT(s.itemcode) as sales_items 
FROM composite_inventories as u 
LEFT JOIN composite_has_inventories as us ON u.id = us.composite_inventory_id 
LEFT JOIN inventories as s ON US.inventory_id = s.id AND us.type='sale'
LEFT JOIN inventories as p ON US.inventory_id = p.id AND us.type='purchase'
GROUP BY u.id

输出:

id  purchase_item_name  sales_item_name     type        purchase_items      sales_items
12  golden              (null)              purchase    Z523,QQ5252,A123    (null)
13  test                demoabc             purchase    Z523,QQ5252         Z523