MySQL GROUP_CONCAT使用子查询

时间:2014-05-15 13:46:12

标签: mysql sql subquery

我有一个GROUP_CONCAT使用子查询但是子查询抛出错误'未知列m.itemid ...'。

我认为这可能是一个范围问题,但我在使用我对MySQL的有限知识找到解决方案时遇到了重大问题。感谢您的帮助,如果您需要更多信息,请告诉我。

SELECT *, 
       CASE parent_item_id 
         WHEN 0 THEN itemid 
         ELSE parent_item_id 
       end  AS order_items_sort, 
       (SELECT Group_concat(id) 
        FROM   (SELECT i.install_delivery_id `id` 
                FROM   machine_serials s 
                       INNER JOIN install_delivery_items i 
                               ON s.install_delivery_item_id = i.id 
                WHERE  s.machine_id = m.itemid 
                GROUP  BY i.install_delivery_id) g) `delivery_id` 
FROM   machines m 
WHERE  m.orderid = 36549 
ORDER  BY order_items_sort, parent_item_id ASC 

1 个答案:

答案 0 :(得分:1)

我猜您可以在外部查询中使用联接,这样您就不需要执行相关子查询

SELECT m.*, 
(CASE parent_item_id 
   WHEN 0 THEN itemid 
   ELSE parent_item_id
END) AS order_items_sort, 
GROUP_CONCAT(DISTINCT i.install_delivery_id)   `delivery_id`
FROM machines m
LEFT JOIN machine_serials s ON(s.machine_id = m.itemid)
LEFT JOIN install_delivery_items i ON s.install_delivery_item_id = i.id
WHERE m.orderid = 36549
GROUP BY m.itemid
ORDER BY order_items_sort, m.parent_item_id ASC