【问题标题】:cursor function to avoid repetition in sqlite database避免sqlite数据库中重复的游标函数
【发布时间】:2020-04-28 15:41:22
【问题描述】:

我有一个 sqlite 数据库,其中包含运输站,我在数据库中复制了一些站,因为它们位于不同的行中,所以我使用了光标:

@Override
public void onLocationChanged(Location location) {
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    float[] results = new float[1];
    Database db = new Database(Stations.this);
    try {
        db.createDataBase();
    } catch (IOException ioe) {
        throw new Error("unable to create database");
    }
    try {
        db.openDataBase();
    } catch (SQLException sqle) {
        throw sqle;
    }
    Cursor c = db.query("Stations", null, null, null, null, null, null);
    if (c.moveToFirst()) {
        do {
            Location.distanceBetween(latitude, longitude, c.getDouble(4), c.getDouble(3), results);
            if (results[0] < 1000) {
                googleMap.addMarker(new MarkerOptions().position(new LatLng(c.getDouble(4), c.getDouble(3))).title(c.getString(1) + " " + c.getString(2)));
                Toast.makeText(this, "nearby station "+ " " + c.getString(2) + "\n", Toast.LENGTH_SHORT).show();
            }

        }
        while (c.moveToNext());
    }
    if (googleMap != null) {
        LatLng googleLocation = new LatLng(latitude, longitude);
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(googleLocation));
    }
}

这会显示站点,但如果该站点在数据库中被提及两次,则会出现重复,我该如何处理这个问题而不显示一个已经看到的站点,因为这两个站点具有不同的 id 但名称相同??

【问题讨论】:

  • 表的列名是什么?
  • @forpas 0 站 id,1 站类型(公共汽车,地铁等),2 站名称,3 经度,4 纬度,5 线 ID。例如,当 X 站在数据库中重复时,这两条记录具有相同的特征但 id 站不同,所以我必须做一些事情,以便当光标找到具有相同站名的记录时,它不会显示它,帮助!
  • 站名是否唯一?

标签: android sqlite cursor android-sqlite


【解决方案1】:

您可以在查询中使用NOT EXISTS

select s.* from stations s 
where not exists (
  select 1 from stations 
  where station_name = s.station_name and station_id < s.station_id
)

替换:

Cursor c = db.query("Stations", null, null, null, null, null, null);

与:

String sql = "select s.* from stations s where not exists (select 1 from stations where station_name = s.station_name and station_id < s.station_id)";
Cursor c = db.rawQuery(sql, null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 2019-03-09
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多