假設你擁有的每行10個技能的限制,你可以正常化skills
列用下面的查詢:
select distinct
s.fname, s.lname,
replace(
substring(substring_index(s.skills, ',', p.pos),
char_length(substring_index(s.skills, ',', p.pos -1)) + 1),
',', ''
) as skill
from
skills s
cross join
(select 1 pos
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
union all select 10
) p on p.pos <= (char_length(s.skills) - char_length(replace(s.skills, ',', ''))) + 1
結果:
| fname | lname | skill |
|-------|-------|--------|
| Jane | Doe | php |
| Jane | Doe | java |
| Jane | Doe | mongo |
| Jane | Doe | mysql |
| Jane | Doe | oracle |
sqlfiddle
(char_length(s.skills) - char_length(replace(s.skills, ',', ''))) + 1
將返回的技能數(計數的逗號)。
replace(
substring(substring_index(s.skills, ',', p.pos),
char_length(substring_index(s.skills, ',', p.pos -1)) + 1),
',', ''
)
將在給定的位置提取技能。
不用內聯創建位置表,您可以使用具有不間斷數字序列的任何現有表。
要再次非規範化的結果,你可以使用GROUP_CONCAT(DISTINCT skill)
:
select
s.fname, s.lname,
group_concat(distinct replace(
substring(substring_index(s.skills, ',', p.pos),
char_length(substring_index(s.skills, ',', p.pos -1)) + 1),
',', ''
)) as skills
from skills s
cross join (
select 1 pos
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
union all select 10
) p on p.pos <= (char_length(s.skills) - char_length(replace(s.skills, ',', ''))) + 1
group by s.fname, s.lname
結果:
| fname | lname | skills |
|-------|-------|-----------------------------|
| Jane | Doe | php,mysql,mongo,oracle,java |
sqlfiddle
這樣沒有技能在列表中出現兩次。
刪除查詢顯示語法錯誤 – VipinS
您能提供錯誤嗎? @vipins – sagi
@VipinS您是否已將'YourTable'更改爲您的實際表名? – sagi