查找包含子字符串

时间:2021-04-29 15:14:41

标签: android sql database android-room

我在 android(SQL) 中使用 Room 数据库,我有一个表,其中包含日期作为列存储为格式为 2000-01-31 的字符串。我想根据它们各自的月份获取表中的所有条目。我正在考虑使用

SELECT * FROM `Transactions` WHERE Date LIKE '%01%

但这样一来,我将不得不为每个月编写单独的查询。 我想按月获取条目并将它们显示在我的 android 应用程序中。

我的桌子看起来像这样... enter image description here

3 个答案:

答案 0 :(得分:0)

这回答了最初提出的问题。

不要对日期使用字符串操作。如果您想要特定年份的特定月份,请使用:

where date >= '2021-01-01' and date < '2021-02-01'

如果你想要所有的一月,那么像这样:

where month(date) = 1

month() 是用于此目的的常用函数,但它可能因您的数据库而异。

答案 1 :(得分:0)

<块引用>

我想根据它们各自的月份获取表中的所有条目

因此,您想要获取所有条目(所有月份),但按某种顺序排序,您可以使用 ORDER BY ASCDESC

SELECT * FROM Transactions ORDER BY Date ASC

答案 2 :(得分:0)

将月份作为参数传递而不是对其进行硬编码,类似于

@Query("select * from Transactions where Date like '%-' || :month || '-%'")
public abstract List<Payment> getDataForMonth(String month);

例如,如果月份是 03,则生成的查询将如下所示。

select * from Transactions where Date like '%-03-%'

此外,将日期存储为 Long(以毫秒为单位)而不是 String 将为查询提供更大的灵活性。

相关问题