用逗号分隔的同一列中的多个值的连接语句

时间:2015-07-23 14:31:22

标签: mysql sql tsql join datatable

我有两张表格如下: -

产品

if((dtTblInvoiceItem != null) && (dtTblInvoiceItem.Rows.Count > 0))

分类

   Product_name |  category_id

   Nutella      |  1,2
   Milk         |  3,4

我正在使用带有SSP库的服务器端处理的数据表来显示产品表。

我需要制作连接语句,以获取每个产品的类别,因为类别列包含逗号分隔的多个值!

无论如何我可以使用MYSQL吗?

修改

预期输出

  cat_id        | name
     1          | dessert
     2          | chocolate
     3          | dairy
     4          | milk

1 个答案:

答案 0 :(得分:2)

假设作为SQL Server,首先,您可以使用CTE从逗号分隔的类别ID获取行到行,然后在cat_id上使用INNER JOIN,您可以获得所需的结果。

SEE DEMO SQL Server

;WITH CTEProduct (Product_name,category_id) 
AS
(
SELECT A.Product_name,  
     Split.a.value('.', 'VARCHAR(100)') AS category_id  
 FROM  
 (
     SELECT Product_name,  
         CAST ('<M>' + REPLACE(category_id, ',', '</M><M>') + '</M>' AS XML) AS Data  
     FROM  Products
 ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a)
) 

Select CTEProduct.category_id,CTEProduct.Product_name,Categories.name 
From CTEProduct 
     INNER JOIN Categories ON CTEProduct.category_id = Categories.cat_id

编辑: - 对于MYSQL,我们必须遵循相同的方法,将逗号分隔的字符串转换为多行,然后转换为INNER JOIN。我不太了解如何将逗号分隔的字符串分隔到MYSQL中的行Refer Here。我在这里使用了相同的答案。

SEE DEMO MYSQL

Select tablename.Product_name,GROUP_CONCAT(Categories.name) name
From (
SELECT Product_name,SUBSTRING_INDEX(SUBSTRING_INDEX(t.category_id, ',', n.n), ',', -1) category_id
  FROM Products t CROSS JOIN 
(
   SELECT a.N + b.N * 10 + 1 n
     FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n
) n
 WHERE n.n <= 1 + (LENGTH(t.category_id) - LENGTH(REPLACE(t.category_id, ',', '')))
  ) tablename
  INNER JOIN Categories ON tablename.category_id = Categories.cat_id
  GROUP BY tablename.Product_name;