SQLite 按列值的一部分过滤记录

SQLite filter records by part of column value

背景:

以下是我拥有的table:

人table:

Id      Name
-------------

1       user1
2       user2

订单table:

Id      Name        Date                        YearMonth       UserId
----------------------------------------------------------------------

1       item1       2015-11-01 02:34:46         2015-11         2
2       item2       2018-09-06 01:04:16         2018-09         1
3       item3       2018-09-23 04:44:21         2018-09         1
4       item4       2018-09-02 11:10:08         2018-09         2
5       item5       2019-11-01 02:54:02         2019-11         1

在 UI 方面,我为每个用户定义了一个微调器,其中填充了 YearMonth 列订单 table。 例如,对于 user1,微调器将填充:

我使用此查询来填充微调器:

 Cursor cursor = db.query("orders",new String[] {"YearMonth"}, "UserId = "+id,
            null, "YearMonth", null, "YearMonth DESC");

// id is a local variable which stores the id of a particular user  

每当我 select 来自微调器的任何 YearMonth 时,该年和月份带来的所有订单都会通过此查询返回:

Cursor cursor = db.query("orders",null,"UserId = ? and YearMonth = ?",
            new String[] {id+"", selectedYearMonth}, null, null, null);

// selectedYearMonth is the value of spinner which is currently selected.

问题:

如果你仔细注意到订单 table 中的 YearMonth 列是不必要的,我可以只用日期列做同样的事情,它也提到了订单的年份和月份,这就是我想要的你的帮助。

你能告诉我一种正确的方法吗?我可以用它来过滤带有部分日期列的上述查询,而无需定义不必要的 YearMonth 列来过滤记录?

您可以轻松查询日期时间,请查看this and

SELECT
  InvoiceId,
  BillingAddress,
  date(InvoiceDate) InvoiceDate,
Total
FROM
  invoices
WHERE
  InvoiceDate NOT BETWEEN '2009-01-03' AND '2013-12-01'
ORDER BY
  InvoiceDate;

另一个例子

SELECT ord_num, ord_amount, ord_date, cust_code, agent_code 
FROM orders 
WHERE ord_date NOT BETWEEN '2008-08-02' AND '2008-30-02';

SQLite 支持以下五种日期和时间函数:

  • 日期(时间字符串,修饰符,修饰符,...)
  • 时间(时间字符串,修饰符,修饰符,...)
  • 日期时间(时间字符串、修饰符、修饰符、...)
  • julianday(时间字符串,修饰符,修饰符,...)
  • strftime(格式、时间字符串、修饰符、修饰符、...)

最好检查一下您是如何创建 table 的,您的日期列必须是日期时间字段。 希望这可以帮助。请提供任何反馈,以便我进一步帮助您。

您可以使用函数 SUBSTR()Date 列 return 一个别名为 YearMonth 的列,以获取日期的前 7 个字符:

Cursor cursor = db.rawQuery(
    "SELECT SUBSTR(Date, 1, 7) YearMonth FROM orders WHERE UserId = ? ORDER BY YearMonth DESC",  
     new String[] {id + ""}
);

您的第二个查询将是:

Cursor cursor = db.rawQuery(
    "SELECT * FROM orders WHERE UserId = ? AND SUBSTR(Date, 1, 7) = ?", 
    new String[] {id + "", selectedYearMonth}
);

修改了 @forpas 的解决方案以最适合问题:

微调器的修改查询:

Cursor cursor = db.query("orders", new String[] {"SUBSTR(orderDate, 1, 7) YearMonth"},
                        "userId = ?", new String[] {String.valueOf(personId)},
                        "YearMonth", null, "YearMonth DESC");    

获取订单修改查询:

Cursor cursor = db.query("orders",null,"userId = ? and SUBSTR(orderDate, 1, 7) = ?",
                         new String[] {personId+"", item}, null, null, null);