我在从表中检索同一日期的最高记录时遇到问题。使用最新版本的 SQLCipher 4.4.2 & 房间数据库版本是 2.2.6。
编号 | 日期值 | 产品名称 | 价格
- 1 | 2021/01/20 | 美国广播公司 | 50
- 2 | 2021/01/20 | XYZ | 60
- 3 | 2021/01/20 | XYZ | 65
- 4 | 2021/01/20 | 美国广播公司 | 60
- 5 | 2021/01/21 | 美国广播公司 | 70
询问:
select t.*, (select t2.id from table_product t2 where t.date_value = t2.date_value order by t2.id desc limit 1) as id1 from table_product t group by t.date_value order by t.date_value
结果:
1 | 2021/01/20 | 美国广播公司 | 50
返回第一条记录,而不是同一日期的最新记录。
我做错了还是有其他方法可以从同一日期的多条记录中获取最新记录?
请帮忙!!
谢谢
测试班
import net.sqlcipher.database.SQLiteDatabase; public class AwesomeTest extends SQLCipherTest { @Override public boolean execute(SQLiteDatabase database) { try { // Add your scenario here database.execSQL("CREATE TABLE table_product (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date_value STRING NOT NULL, date_time_stamp LONG NOT NULL, product_name STRING NOT NULL, price INTEGER NOT NULL)"); database.execSQL("INSERT INTO table_product (id, date_value, date_time_stamp, product_name, price) VALUES ('1', '2021/02/27', '1614364210000', 'ABC', '10')"); database.execSQL("INSERT INTO table_product (id, date_value, date_time_stamp, product_name, price) VALUES ('2', '2021/02/27', '1614364211000', 'XYZ', '11')"); database.execSQL("INSERT INTO table_product (id, date_value, date_time_stamp, product_name, price) VALUES ('3', '2021/02/27', '1614364212000', 'ABC', '13')"); database.execSQL("INSERT INTO table_product (id, date_value, date_time_stamp, product_name, price) VALUES ('4', '2021/02/28', '1614450600000', 'ABC', '14')"); String query = "SELECT t.*, (SELECT t2.id from table_product t2 where t.date_value = t2.date_value order by t2.id desc " + "limit 1) as id1 from table_product t group by t.date_value order by t.date_value"; Cursor cursor = database.rawQuery(query, new String[]{}); if(cursor != null) { Log.i("TEST", "Record count is " + cursor.getCount()); while(cursor.moveToNext()) { int index1 = cursor.getColumnIndex("price"); int price = cursor.getInt(index1); Log.i("TEST", "product price is " + price); } cursor.close(); } return true; } catch (Exception e) { return false; } } @Override public String getName() { return "Awesome Test"; } }