简体   繁体   中英

MySQL- How to fetch multiple values of same column using a single SQL query?

I need to store each values from the Resultset to float variables. Currently I am using multiple SQL queries for this. I have combined the queries

float Wb_SWLat = 0;
float Wb_NELat = 0;
float Wb_SWLon = 0;
float Wb_NELon = 0;

float Nb_SWLat = 0;
float Nb_NELat = 0;
float Nb_SWLon = 0;
float Nb_NELon = 0;

//Query:
String qryWb = "select zone, SW_lat, SW_lon, NE_lat, NE_lon from tbl_zones";

try {
    Statement stmt = (Statement) conn.createStatement();

    Wb=stmt.executeQuery(qryWb);
    while(Wb.next()){ 
        if (Wb.getString("zone") == "west"){
            Wb_SWLat=Wb.getFloat("SW_lat");
            Wb_NELat=Wb.getFloat("NE_lat");
            Wb_SWLon=Wb.getFloat("SW_lon");         
            Wb_NELon=Wb.getFloat("NE_lon");
        }
        else if (Wb.getString("zone") == "north"){
            Nb_SWLat=Wb.getFloat("SW_lat");
            Nb_NELat=Wb.getFloat("NE_lat");
            Nb_SWLon=Wb.getFloat("SW_lon");         
            Nb_NELon=Wb.getFloat("NE_lon");
        }
    }
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Is this is the efficient way? or right way of doing this?

Below is My MySQL table, tbl_zones:-

pk_id  jn    zone     SW_lat     SW_lon     NE_lat     NE_lon
--------------------------------------------------------------
 1     j1    west     9.99404    76.3567    9.99419    76.3572
 2     j2    north    9.99419    76.3572    9.99471    76.3573
 3     j3    south    9.99384    76.3572    9.99413    76.3573
 4     j4    east     9.99413    76.3574    9.99426    76.3577

Use the OR operator in the where clause. That will get you both lines needed in one query (and roundtrip time to DB ).

Now, in order to identify each fetched line, add zone to your select statement, and use an if clause in your code to identify the current line in the ResultSet object.

The query should look something like this:

select SW_lat, SW_lon, NE_lat, NE_lon, zone from tbl_zones where zone='west' OR zone='north

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM