首页 > 解决方案 > 避免sqlite数据库中重复的游标函数

问题描述

我有一个 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));
    }
}

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

标签: androidsqlitecursorandroid-sqlite

解决方案


您可以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);

推荐阅读