游标函数,以避免在sqlite数据库中重复

问题描述 投票:0回答:1

我有一个包含运输站的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但相同名称的站点,则该如何显示?

sqlite android-studio google-maps cursor google-nearby
1个回答
0
投票

您可以在查询中使用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);

with:

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);
© www.soinside.com 2019 - 2024. All rights reserved.