SQLite按列值的部分筛选记录

huangapple go评论80阅读模式
英文:

SQLite filter records by part of column value

问题

背景:

以下是我拥有的表:

Persons表:

Id      姓名
-------------

1       用户1
2       用户2

Orders表:

Id      姓名      日期                      年月          用户Id
----------------------------------------------------------------------

1       项目1      2015-11-01 02:34:46      2015-11      2
2       项目2      2018-09-06 01:04:16      2018-09      1
3       项目3      2018-09-23 04:44:21      2018-09      1
4       项目4      2018-09-02 11:10:08      2018-09      2
5       项目5      2019-11-01 02:54:02      2019-11      1

在用户界面上,我为每个用户定义了一个微调器(spinner),其中填充了订单表的“年月”列。
例如,对于“用户1”,微调器将填充以下内容:

  • 2019-11
  • 2018-09

我使用以下查询填充微调器:

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

// id是存储特定用户id的局部变量

每当我从微调器中选择任何年月时,所有在该年月购买的订单都会通过以下查询返回:

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

// selectedYearMonth是当前选定的微调器值。

问题:

如果您仔细观察,订单表中的“年月”列是不必要的,我只需使用日期列就可以表示订单的年份和月份,这就是我想要您的帮助的地方。

您能否向我展示一种正确的方法,通过日期列的一部分筛选上述查询,而无需为仅筛选记录而定义不必要的“年月”列?

英文:

Background:

Following are the tables that I have:

Persons table:

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

1		user1
2		user2

Orders 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

On the UI side I have defined a spinner for each user which is populated with YearMonth column of orders table.
For example for user1 the spinner would be populated with:

  • 2019-11
  • 2018-09

I use this query to populate the spinner:

 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  

And whenever I select any of the YearMonth from the spinner all the orders brought on that year and month get returned with this query:

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.

Problem:

If you notice carefully the column YearMonth in orders table is unnecessary I could have done the same with just date column which also mentions the year and month of orders and this is where I want your help.

Can you show me a right way with which I can filter the above queries with part of date column without the need of defining the unnecessary YearMonth column for just filtering the records ?

答案1

得分: 1

你可以使用函数 SUBSTR() 从列 Date 中返回一个列的别名为 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}
);
英文:

You can return a column aliased YearMonth from the column Date by using the function SUBSTR(), to get the first 7 chars of the date:

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

and your 2nd query will be:

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

答案2

得分: 0

你可以轻松地查询日期时间,请查看这个链接与你的问题相关的答案

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支持以下五个日期和时间函数:

  • date(timestring, modifier, modifier, ...)
  • time(timestring, modifier, modifier, ...)
  • datetime(timestring, modifier, modifier, ...)
  • julianday(timestring, modifier, modifier, ...)
  • strftime(format, timestring, modifier, modifier, ...)

请确保检查你创建表格的方式,你的Date列必须是一个DateTime字段。希望这能帮助你。如果有任何反馈,请告诉我,我可以继续帮助你。

英文:

You can query date time with ease, please have a look at this and answer relates to your problem

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

Another example

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 supports five date and time functions as follows:

  • date(timestring, modifier, modifier, ...)
  • time(timestring, modifier, modifier, ...)
  • datetime(timestring, modifier, modifier, ...)
  • julianday(timestring, modifier, modifier, ...)
  • strftime(format, timestring, modifier, modifier, ...)

better check how you creating the table, your Date column must be a DateTime field.
hope this helps. give any feedback so I can help you further.

答案3

得分: 0

根据 @forpas 的解决方案进行了修改,以最适应该问题:

修改了 Spinner 的查询:

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);
英文:

Modified the solution of @forpas to best suite the Question:

Modified query for Spinner:

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

Modified query of getting orders:

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

huangapple
  • 本文由 发表于 2020年7月24日 12:50:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63067033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定