【问题标题】:MySQL: Check if any value in list satisfies a conditionMySQL:检查列表中的任何值是否满足条件
【发布时间】:2022-06-13 20:08:07
【问题描述】:

假设我有一个名为 Seasons 的表格:

... start_month end_month
... 2 6
... 3 4
... ... ...

我需要编写一个查询,其中对于给定的月份列表返回满足列表中至少 1 个月的条件的所有 季节start_month <= month <= 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;
        }
    }

}

我不知道如何写这个,我想使用 ANY 运算符,直到我发现 ANY 只适用于表而不是列表,我想把它写成一个将列表转换为表的子查询,但是我不知道这是否可能,我在 MySQL 文档中找不到任何内容。任何帮助将不胜感激。

【问题讨论】:

    标签: java mysql sql jdbc


    【解决方案1】:

    在 where 子句中,您需要每个月都有一个 OR 条件。
    您可以在循环中生成它,然后 concat 或类似的东西。

    例如,您对输入 1、3、4、7 的最终查询将如下所示:

    SELECT *
    FROM seasons as s
    WHERE 1 between start_month and end_month
    OR 3 between start_month and end_month
    OR 4 between start_month and end_month
    OR 7 between start_month and end_month
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 2018-05-09
      • 2012-10-01
      • 1970-01-01
      • 2019-03-16
      相关资源
      最近更新 更多