更改mysql查询以组合多个列而不是单独的行

时间:2015-08-29 11:56:21

标签: mysql sql select group-by group-concat

我有2张这样的表:

Table: Company
id| Name         | Area
1 | Company A    | New York
2 | Company B    | New York
3 | Company C    | Chicago

Table: Service
id| Type
1 | Service
1 | Delivery
2 | Hotel
2 | Restaurants
3 | Movers

我想像纽约这样的结果(没有芝加哥)得到结果:

Name      | Area    | Type
Company A | New York| Service, Delivery
Company B | New York| Hotel, Restaurants

但我反而得到了这个:

Name      | Area     | type
Company A | New York | Service
Company A | New York | Delivery
Company B | New York | Hotel
Company B | New York | Restaurants

我尝试使用distinct和concat来解决我的问题,但查询没有结束,而是在运行超过6秒后超时。如果我运行查询以获得我现在得到的结果,我得到的结果不到1秒。

以下是我到目前为止所尝试的查询:

select p1.Name,
GROUP_CONCAT(p2.Type) from company as p1, service as p2
GROUP BY p1.CompanyName
LIMIT 10;

结果:超时

select DISTINCT company.Name from company
LEFT JOIN service
ON company.Number = service.Number AND service.Type LIKE '% York'
Limit 50;

结果:永远不会结束(甚至没有超时)

select p1.Name, p2.type from company as p1, service as p2
where p1.id = p2.id
LIMIT 10;

结果: 显示真的搞砸了结果,这是不可能的:

Name      | Type
Company A | Hotel
Company B | Delivery
Company B | Restaurants

数据库最初是Microsoft Access,我在那里得到了这样的结果,不熟悉微软访问我认为微软必须遇到问题,并试图在mysql中执行查询,但同样的问题发生在那里......如果我尝试手动计算数据显示的内容根本不符合,这让我真的很困惑...有人可以查看我的查询并告诉我我做错了什么? THX!

2 个答案:

答案 0 :(得分:0)

使用内部联接来获取匹配的记录并按公司ID分组结果。

以下是查询:

 select c.name,c.area,group_concat(s.Type) as type 
 from Company c inner join service s on c.id=s.id
 where c.area='New York'
 group by s.id;

答案 1 :(得分:0)

试试这个:

SELECT c.Name, c.Area, GROUP_CONCAT(s.Type SEPARATOR ', ') AS TYPE
FROM Company AS c 
LEFT JOIN Service AS s ON c.id = s.id 
WHERE c.Area = 'New York'
GROUP BY c.id;