假設我有下表稱為Seasons:
| ... | 開始月 | end_month |
|---|---|---|
| ... | 2 | 6 |
| ... | 3 | 4 |
| ... | ... | ... |
我需要撰寫一個查詢,對于給定的月份串列,回傳所有Seasons滿足串列中至少 1 個月為: 的條件的查詢start_month <= month <= end_month。
除了 where 子句外,我已將此查詢撰寫為使用 JDBC 的本機查詢。
@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 檔案中找不到任何內容。
uj5u.com熱心網友回復:
在您的 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)
uj5u.com熱心網友回復:
實作此目的的一種方法是:
select s.*
from (select 1 as mn union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8
union select 9 union select 10 union select 11 union select 12) as a
inner join season s on a.mn between s.start_month and s.end_month
where a.mn in (:flexibleTypeMonths);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493984.html
