我尝试使用union,pivoting和使用函数[关闭]

问题描述 投票:-4回答:2

我尝试搜索以下要求的解决方案。

输入:

ID  Name  Subject
1   james Maths

输出:

ID  Name  Subject
1    j    Maths
1    a    Maths
1    m    Maths
1    e    Maths
1    s    Maths

这里的任何人都可以帮我查询吗?

mysql sql
2个回答
1
投票

您可以使用MySQL的SubString函数来获取第一个,第二个,第三个......字符。

SubString([String],[Position],[Length])

select ID, SUBSTRING(Name, 1, 1) as Name, Subject from yourtable

在这个例子中,您应该能够编写自己的函数,以存档您想要的输出。


0
投票

这将通过递归查询来完成,但到目前为止MySQL还没有递归查询。

如果你知道最大字母数(例如7),你就可以做到

select id, name, subject
from
(
  select id, substr(name, 1, 1) as name, subject from mytable
  union all
  select id, substr(name, 2, 1) as name, subject from mytable
  union all
  select id, substr(name, 3, 1) as name, subject from mytable
  union all
  select id, substr(name, 4, 1) as name, subject from mytable
  union all
  select id, substr(name, 5, 1) as name, subject from mytable
  union all
  select id, substr(name, 6, 1) as name, subject from mytable
  union all
  select id, substr(name, 7, 1) as name, subject from mytable
)
where name <> '';
© www.soinside.com 2019 - 2024. All rights reserved.