检查列表中的任何值是否满足条件
假设我有下表称为seasons
:
... | start_month | end_month |
---|---|---|
... | 2 | 6 |
... | 3 | 4 |
... | ... ... | ... |
我需要编写一个查询给定的月份列表,返回所有满足列表中至少1个月的条件的季节
:start_month< = noter< = end_month
。
我已经将此查询写为JDBC的本机查询,除了WHERE子句。
@Repository
public class SeasonsRepositoryImpl implements SeasonsRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public List<SeasonsProjection> findByMonths(List<Integer> months) {
String query = "select * " +
"from seasons as s" +
"where ...."
try {
return em.createNativeQuery(query)
.setParameter("months", months)
.unwrap(org.hibernate.query.NativeQuery.class)
.setResultTransformer(Transformers.aliasToBean(SeasonsProjection.class))
.getResultList();
} catch (Exception e) {
log.error("Exception with an exception message: {}", e.getMessage());
throw e;
}
}
}
我不知道如何写这篇文章,我想到了使用任何操作员,直到我发现任何只能与桌子一起使用而不列表,我认为将其写为将列表转换为表的子查询,但我不喜欢t知道是否可以,我在MySQL文档中找不到任何东西。
Suppose I have the following table called Seasons
:
... | start_month | end_month |
---|---|---|
... | 2 | 6 |
... | 3 | 4 |
... | ... | ... |
I need to write a query which, for a given list of months, returns all the Seasons
that satisfy the condition where at least 1 month in the list is: start_month <= month <= end_month
.
I've written this query as a native query with JDBC, except the where clause.
@Repository
public class SeasonsRepositoryImpl implements SeasonsRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public List<SeasonsProjection> findByMonths(List<Integer> months) {
String query = "select * " +
"from seasons as s" +
"where ...."
try {
return em.createNativeQuery(query)
.setParameter("months", months)
.unwrap(org.hibernate.query.NativeQuery.class)
.setResultTransformer(Transformers.aliasToBean(SeasonsProjection.class))
.getResultList();
} catch (Exception e) {
log.error("Exception with an exception message: {}", e.getMessage());
throw e;
}
}
}
I have no idea how to write this, I thought of using the ANY operator until I found out that ANY only works with tables and not lists, I thought of writing this as a subquery with converting the list to a table, but I don't know if that's possible, I couldn't find anything in the MySQL documentation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的Where条款中,您需要每个月的条件或条件。
您可以在循环中生成它,然后进行concat或类似的东西。
例如,您对1,3,4,7的输入的最终查询将如下:
In your where clause, you will want to have an OR conditions for each month.
You can generate it in a loop and then concat or something similar.
Your final query for input of 1,3,4,7 for example will look as follows:
实现此目的的一种方法是:
One way to accomplish this is: