MST

星途 面试题库

面试题:Flutter SQLite数据库复杂查询与索引优化

假设在Flutter应用的SQLite数据库中有一个包含大量订单数据的表,表结构包含订单ID、客户ID、订单金额、订单时间等字段。现在需要查询某个客户在特定时间段内,订单金额大于某个阈值的所有订单信息,且按订单金额降序排列。请阐述如何设计索引来优化这个复杂查询,并写出完整的SQL查询语句以及在Flutter中执行该查询的代码。
44.1万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

索引设计

为了优化这个查询,应该在 客户ID订单时间订单金额 字段上创建复合索引。这样的索引顺序可以有效地支持查询,因为它匹配了查询中的筛选和排序条件。

SQL查询语句

SELECT * 
FROM 订单表
WHERE 客户ID =? 
  AND 订单时间 BETWEEN? AND? 
  AND 订单金额 >?
ORDER BY 订单金额 DESC;

这里 ? 是占位符,在实际执行查询时会被具体的值替换。

Flutter中执行该查询的代码

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

Future<List<Map<String, dynamic>>> getOrders(int customerId, DateTime startDate, DateTime endDate, double threshold) async {
  final databasePath = await getDatabasesPath();
  final path = join(databasePath, 'your_database.db');

  final database = await openDatabase(
    path,
    version: 1,
    onCreate: (Database db, int version) async {
      await db.execute('''
        CREATE TABLE 订单表 (
          订单ID INTEGER PRIMARY KEY,
          客户ID INTEGER,
          订单金额 REAL,
          订单时间 TEXT
        )
      ''');
    },
  );

  List<Map<String, dynamic>> result = await database.query(
    '订单表',
    where: '客户ID =? AND 订单时间 BETWEEN? AND? AND 订单金额 >?',
    whereArgs: [customerId, startDate.toIso8601String(), endDate.toIso8601String(), threshold],
    orderBy: '订单金额 DESC',
  );

  return result;
}

在实际使用中,可以这样调用上述函数:

void main() async {
  int customerId = 1;
  DateTime startDate = DateTime(2023, 1, 1);
  DateTime endDate = DateTime(2023, 12, 31);
  double threshold = 100.0;

  List<Map<String, dynamic>> orders = await getOrders(customerId, startDate, endDate, threshold);
  print(orders);
}

请注意,上述代码假设你已经在 pubspec.yaml 中添加了 sqflite 依赖,并且确保数据库文件路径和表结构与实际情况相符。同时,时间格式需要与数据库中存储的格式一致,这里假设为 ISO8601 格式。