2014-10-28 156 views
1

得到字符串列表的字符串我有如下表表A:如何使用SQL查询

+--------+----------------------+ 
| Id |   Ref   | 
+--------+----------------------+ 
| 1 | RN1-102,RN2-103 | 
| 2 | RN1-106   | 
| 3 | RN2-203   | 
| 4 | NULL    | 
| 5 | RN1-104|,RN2-107 | 
| 6 | RN1-101,RN2-105 | 
| 7 | RN1-100,RN2-109 | 
+--------+----------------------+ 

我需要(从TableA的不同REF)一个输出如下:

+--------------------+ 
| Distinct Ref data | 
+--------------------+ 
|  RN1-100  | 
|  RN1-101  | 
|  RN1-102  | 
|  RN1-104  | 
|  RN1-106  | 
|  RN2-103  | 
|  RN2-105  | 
|  RN7-107  | 
|  RN2-109  | 
|  RN2-203  | 
+--------------------+ 

我试着用下面的查询:

select distinct Ref from tableA 

请帮我..

+0

架构是一个不好的做法,我认为。但尝试检查了这一点,它有相同的问题:http://stackoverflow.com/questions/17308669/reverse-group-concat-in-mysql – 2014-10-28 05:00:54

+0

你提供的表是不是一个好的做法(多个值在一个行)。尝试更改架构。 – theDbGuy 2014-10-28 05:32:12

回答

1

尝试使用此

SELECT distinct Split.a.value('.', 'VARCHAR(100)') REF 
      FROM (select ID,Cast ('<M>' 
           + replace(Replace(REF, ',', '</M><M>'),'&','&amp;') 
           + '</M>' AS XML) AS Data from #Table) AS A 
        CROSS APPLY Data.nodes ('/M') AS Split(a) 
0

这个问题类似于this question我之前回答。我在这个答案中提出了两种方法,一种是使用递归另一种方法。

但如果你已经有一个表存储ref键,您有第三个选择是这样的:

create table ref_table (ref varchar(10), ref_name varchar(100), primary key (ref)); 

select 
    r.ref 
from 
    ref_table r 
where 
    EXISTS (
     select 1 
     from tableA a 
     where a.ref like '%'+r.ref+'%' -- or ','+a.ref+',' like '%,'+r.ref+',%' 
     ) 

SQL FIDDLE DEMO

0
SELECT distinct Split.a.value('.', 'VARCHAR(100)') REF 
      FROM (select ID,Cast ('<M>' 
           + replace(Replace(REF, ',', '</M><M>'),'&','&amp;') 
           + '</M>' AS XML) AS Data from #Table) AS A 
        CROSS APPLY Data.nodes ('/M') AS Split(a)