Search records having comma seperated values that contains any element from the given list

随声附和 提交于 2020-01-05 07:48:22

问题


I have a domain class Schedule with a property 'days' holding comma separated values like '2,5,6,8,9'.

Class Schedule {
   String days
   ...
}

Schedule schedule1 = new Schedule(days :'2,5,6,8,9')
schedule1.save()

Schedule schedule2 = new Schedule(days :'1,5,9,13')
schedule2.save()

I need to get the list of the schedules having any day from the given list say [2,8,11].

Output: [schedule1]

How do I write the criteria query or HQL for the same. We can prefix & suffix the days with comma like ',2,5,6,8,9,' if that helps.

Thanks,


回答1:


Hope you have a good reason for such denormalization - otherwise it would be better to save the list to a child table.

Otherwise, querying would be complicated. Like:

  def days = [2,8,11]
  // note to check for empty days
  Schedule.withCriteria {
    days.each { day ->
      or {
        like('username', "$day,%") // starts with "$day"
        like('username', "%,$day,%")
        like('username', "%,$day") // ends with "$day"
      }
    }
  }



回答2:


In MySQL there is a SET datatype and FIND_IN_SET function, but I've never used that with Grails. Some databases have support for standard SQL2003 ARRAY datatype for storing arrays in a field. It's possible to map them using hibernate usertypes (which are supported in Grails).

If you are using MySQL, FIND_IN_SET query should work with the Criteria API sqlRestriction: http://grails.org/doc/latest/api/grails/orm/HibernateCriteriaBuilder.html#sqlRestriction(java.lang.String) Using SET+FIND_IN_SET makes the queries a bit more efficient than like queries if you care about performance and have a real requirement to do denormalization.



来源:https://stackoverflow.com/questions/5630505/search-records-having-comma-seperated-values-that-contains-any-element-from-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!