切割字段里的字符串进行查询

假设一个人可以对应很多年级,但是因为设姓名为主键一个人只能有一条记录,所以保存的时候把年级组合成字符串入库了,那查询的时候怎么能切割字段里的字符串查到特定年级的人呢?

如果直接用select * from table where 年级='2019',那B就不会显示出来,但是我希望能显示出来

image.png

FineReport yixi6978 发布于 2023-4-4 20:00
1min目标场景问卷 立即参与
回答问题
悬赏:3 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共2回答
最佳回答
0
CD20160914Lv8专家互助
发布于2023-4-4 20:03(编辑于 2023-4-4 20:10)

先用数据库拆分出来对应的行

比如oracle里面类似这样

select  regexp_substr(a.REGIONS,'[^,]+',1,level) as REGION,rownum as irow

from (select 'AAA,BBB,CCC,DDD' as REGIONS from dual )a

connect by level <= REGEXP_COUNT(a.REGIONS,'[^,]+')

image.png

mysql类似这样

select 

substring_index(

    substring_index(

      t.com,

      ',',

      b.help_topic_id + 1

    ),

    ',' ,- 1

  ) AS com_row,

  t.myname

 from (

select '2021,2019' as com,'张三' as myname 

union all

select '2019' as com,'李四' as myname 

) t 

JOIN mysql.help_topic b ON b.help_topic_id < (

  length(t.com) - length(

    REPLACE (t.com, ',', '')) + 1)

image.png

最佳回答
0
axingLv6专家互助
发布于2023-4-5 00:42

把你的查询语句改成这样就好了

select * from table where ','+年级+','  like ',2019,'

年级设置参数时:

select * from table where ','+年级+','  like ',${年级},'

  • 3关注人数
  • 405浏览人数
  • 最后回答于:2023-4-5 00:42
    请选择关闭问题的原因
    确定 取消
    返回顶部