MYSQL Concat多行并加入多个表

时间:2017-03-11 01:28:58

标签: mysql group-by inner-join distinct group-concat

我有以下表结构:

 tMaster
 City   ClientId    ProductId   
 -------------------------------------
 1          1       1
 1          1       N
 2          1       1   
 2          2       3
 N          N       N

 tCity
 CityId   CityName      
 ----------------------
 1     City1   
 2     City2   
 N     CityN  

 tClient
 ClientId   ClientName      
 ----------------------
 1          ClientName1   
 2          ClientName2   
 N          ClientNameN  

 tProduct
 ProductId  ProductName
-------------------------------------
 1          ProductName1 
 2          ProductName2    
 3          ProductName3
 N          ProductNameN

我的SQL是:

 SELECT idCity, 
 GROUP_CONCAT(DISTINCT ClientId , "|" ,ProductId ORDER BY ClientId) AS StringResult
 FROM tMaster
 GROUP BY idCity
 ORDER BY idCity

所以,我的结果是:

 idCity StringResult
 ---------------------------------------------------------
 1      ClientId1|ProductId1,ClientIdN|ProductIdN
 2      ClientId1|ProductId1,ClientId2|ProductId3

但我需要从tCity,tClient和tProduct获取CityName,ClientName和ProductName

 idCity City    StringResult
 ---------------------------------------------------------
 1      City1   ClientId1|ClientName1|Product1|ProductName1,ClientN|ClientNameN|ProductIdN|ProductNameN
 2      City2   ClientId1|ClientName1|ProductId1|ProductName1,ClientId2|ClientName2|ProductId3|ProductName3

有什么办法吗?

1 个答案:

答案 0 :(得分:1)

您没有在SELECT语句中包含这些列,因此您不会在输出中获得这些列。尝试这样的事情:

SELECT idCity, CityName, ClientName, ProductName
GROUP_CONCAT(
    DISTINCT tMaster.ClientId , "|" , CityName, "|", ClientName, "|", 
    ProductId , "|", ProductName ORDER BY tMaster.ClientId) AS StringResult
FROM tMaster
INNER JOIN tCity ON tMaster.city = tCity.CityId
INNER JOIN tClient ON tMaster.ClientId = tClient.ClientId
INNER JOIN tProduct ON tMaster.ProductId = tProduct.ProductId

由于其中一些列名不明确,您需要包含表名,即tMaster.ClientId。

这应该有效。我需要设置一个快速模式来验证。