I want to combine these 2 sql queries into 1, is that possible? I am not a SQL expert unfortunately.
My current code snippet with the 2 queries is as follows:
if(myFlag.equals("") || isFlagPirate.equals("N")){
//get list of available ship id, ship name as options for the ship dropdown list
sqlShipListString =
"select distinct ship.ship_id, ship.name from admiralty_branch " +
"left join ship on ship.ship_id=admiralty_branch.ship_id " +
"where admiralty_branch_id= " + admiraltyid +
" order by ship.name";
}else{
if(isFlagPirate.equals("Y")){
//get list of available ship id, ship name as options for the ship dropdown list
sqlShipListString =
"select distinct ship.ship_id, ship.name from ship " +
"left join ship_type on ship.ship_id=ship_type.ship_id " +
"left join fleet on ship_type.fleet_id=fleet.fleet_id " +
"where fleet_id= " + fleetId +
" order by ship.name";
}
}
As requested, table structures:
**ship**
ship_id
name
**admiralty_branch**
admiralty_branch_id
ship_id
**ship_type**
ship_id
fleet_id
**fleet**
fleet_id
Here is an ugly solution. The 2 left joins for pirates vs 1 for non pirates makes for a difference in the pattern. I wouldn't refactor for just these 2 queries. If you have more you could consider creating an sqlbuilder of some sort.
public String getSql(String isFlagPirate)
{
if(myFlag .equals("") || isFlagPirate.equals("N")){
//get list of available ship id, ship name as options for the ship dropdown list
return
buildSql("admiralty_branch ", "ship on ship.ship_id=admiralty_branch.ship_id ",
"admiralty_branch_id", admiraltyid);
}else{
if(isFlagPirate.equals("Y")){
//get list of available ship id, ship name as options for the ship dropdown list
return buildSql("ship ", "ship_type on ship.ship_id=ship_type.ship_id left join fleet on ship_type.fleet_id=fleet.fleet_id ",
"fleet_id", fleetId);
}
return "";
}
}
protected String buildSql(String table, String leftjoin, String whereFieldName, String whereFieldValue)
{
return "select distinct ship.ship_id, ship.name from "+table +
"left join "+leftjoin +
"where "+whereFieldName+"= " + whereFieldValue +
" order by ship.name";
}
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.