MySQL子查询提取多个结果

时间:2014-07-17 18:16:21

标签: php mysql subquery group-concat

我有不同'manufacturer'字段的重复记录。我尝试GROUP BY i.stocknumber但是只删除了一条记录而没有收集其他制造商的结果。

某些记录中有NULL个制造商字段,我尝试在子查询中使用GROUP_CONCAT来忽略"制造商"的不同结果。

这是我当前的疑问:

SELECT i.id,i.stocknumber,m.manufacturer
FROM inventory i
INNER JOIN makes mk on i.make = mk.id 
INNER JOIN models md on i.model = md.id 
INNER JOIN classes cl on i.class = cl.id 
LEFT JOIN ( 
            SELECT idm.id, idm.inventory_id, dm.manufacturer AS 'manufacturer' 
            FROM display_manufacturers dm 
            INNER JOIN inventory_display_manufacturers idm ON dm.id = idm.display_manufacturer_id 
           ) m ON i.id = m.inventory_id 
-- GROUP BY i.stocknumber
ORDER BY i.stocknumber

我得到的结果是:

enter image description here

有关通过连接manufacturer字段对重复记录进行分组的任何想法吗?

注意:我已在子查询上尝试过GROUP_CONCAT

期望的结果:

id   | stocknumber | manufacturer
----------------------------------
946  | 011A        | NULL
907  | 1001        | Sports Coach, Coachmen
1032 | 1001x       | Sports Coach

等...

2 个答案:

答案 0 :(得分:1)

你在找这个吗?

SELECT i.id, i.stocknumber, group_concat(distinct m.manufacturer) as manufacturers
. . .
GROUP BY i.stocknumber

编辑:

此版本明确将您的查询用作子查询。它不应该把所有制造商放在同一行:

select stocknumber, group_concat(distinct manufacturer) as manufacturers
from (SELECT i.id,i.stocknumber,m.manufacturer
      FROM inventory i
      INNER JOIN makes mk on i.make = mk.id 
      INNER JOIN models md on i.model = md.id 
      INNER JOIN classes cl on i.class = cl.id 
      LEFT JOIN ( 
            SELECT idm.id, idm.inventory_id, dm.manufacturer AS 'manufacturer' 
            FROM display_manufacturers dm 
            INNER JOIN inventory_display_manufacturers idm ON dm.id = idm.display_manufacturer_id 
           ) m ON i.id = m.inventory_id
     ) t
GROUP BY stocknumber ;

答案 1 :(得分:0)

如果您要执行的操作是删除NULL字段,则只需添加除NULL字段之外的WHERE条件

SELECT i.id,i.stocknumber,m.manufacturer
FROM inventory i
INNER JOIN makes mk on i.make = mk.id 
INNER JOIN models md on i.model = md.id 
INNER JOIN classes cl on i.class = cl.id 
LEFT JOIN ( 
            SELECT idm.id, idm.inventory_id, dm.manufacturer AS 'manufacturer' 
            FROM display_manufacturers dm 
            INNER JOIN inventory_display_manufacturers idm ON dm.id = idm.display_manufacturer_id 
           ) m ON i.id = m.inventory_id 
WHERE m.manufacturer IS NOT NULL
-- GROUP BY i.stocknumber
ORDER BY i.stocknumber