如何动态生成具有特定列的sql查询

时间:2012-09-12 07:22:07

标签: java sql

我有几张桌子。我也有查询。我的问题是使用Java动态生成SQL查询。

我在单独的表格中有以下字段:

 Collumn name          status
po_number,               Y
unit_cost,               Y
placed_date ,            Y
date_closed,             Y
scheduled_arrival_date   Y
date_closed              Y 
order_quantity           Y
roll_number              N
product_sku              N
product_category_name    N
rec_vendor_quantity      Y  
vendor_name              Y
et_conversion_unit_quantity Y

我必须在状态为Y时生成查询,这里的问题是上述列的一段时间

以下查询是上述的输出:

这里我已经包含了所有列但我必须删除状态为N的列,请帮助我使用java来解决查询。

select
pi.po_number,poi.unit_cost,pi.placed_date CreateDate,
case when isnull(pi.date_closed) then pi.scheduled_arrival_date  
else pi.date_closed end as ReceviedDate,
poi.order_quantity,poi.roll_number,p.product_sku product_name,
pc.product_category_name,poi.rec_vendor_quantity,pv.vendor_name,p.et_conversion_unit_quantity,pi.note
from
purchase_order as pi,
purchase_order_inventory as poi,
product_vendors as pv,
products AS p,
product_categories AS pc
where
pi.purchase_order_id=poi.purchase_order_id and
pc.product_category_id=p.product_category_id and
poi.product_id = p.product_id and
poi.product_category_id=pc.product_category_id and
pi.vendor_id=pv.product_vendor_id and
( ( pi.date_closed  >= '2012-01-01' and pi.date_closed <='2012-09-05 23:59:59' ) 
or ( pi.scheduled_arrival_date  >= '2012-01-01' and pi.scheduled_arrival_date <='2012-09-05 23:59:59') ) and
pi.po_type=0 
and pi.status_id = 0 and  poi.transaction_type = 0  
order by pi.po_number 

更新:

QUERY:STEP 1:

SELECT rcm.id,rcm.tablename,rcm.columnname,rcm.size,rcm.displayorder,rcm.isactive FROM report_customise_master rcm where rcm.tablename !='employee' and rcm.isactive='Y' order by rcm.displayorder;

第2步: 用于构造查询的Java方法:

public Map getComplexReportQuery() {
    String query = "SELECT rcm.id,rcm.tablename,rcm.columnname,rcm.size,rcm.displayorder,rcm.isactive FROM report_customise_master rcm where rcm.tablename !='employee' and rcm.isactive='Y' order by rcm.displayorder;";
    String tableName = "", from = "", select = "";
    StringBuffer sb = new StringBuffer();
    Map<String, List<String>> resultsMap = new LinkedHashMap<String, List<String>>();
    Map<String, String> displayOrderMap = new LinkedHashMap<String, String>();
    Map queryMap = new LinkedHashMap();
    if (!query.isEmpty() || query.length() > 0) {
        sb.append(query);
    }

    Connection connection = getConnection();
    if (connection != null) {
        try {
            PreparedStatement reportQueryPS = connection.prepareStatement(sb.toString());
            ResultSet reportQuery_rst = reportQueryPS.executeQuery();
            List<String> tables = new ArrayList<String>();;
            if (reportQuery_rst != null) {
                StringBuilder selectQuery = new StringBuilder(" SELECT ");
                StringBuilder fromQuery = new StringBuilder(" FROM ");
                while (reportQuery_rst.next()) {
                    tableName = reportQuery_rst.getString("tablename");
                    List<String> columns = resultsMap.get(tableName);
                    if (columns == null) {
                        columns = new ArrayList<String>();
                        resultsMap.put(tableName, columns);
                    }
                    columns = resultsMap.get(tableName);
                    String columnName = reportQuery_rst.getString("columnname");

                    columns.add(columnName);
                }
                tableName = "";
                for (Entry<String, List<String>> resultEntry : resultsMap.entrySet()) {
                    tableName = resultEntry.getKey();
                    List<String> columns = resultEntry.getValue();
                    int i = 0;
                    for (String column : columns) {
                        selectQuery.append(tableName + "." + column);
                        if (i != columns.size()) {
                            selectQuery.append(",");
                        } else {
                            selectQuery.append("");
                        }
                        i++;
                    }
                    if (!tables.contains(tableName)) {
                        tables.add(tableName);
                    }
                }
                //to remove comma at the end of line
                select = selectQuery.toString().replaceAll(",$", "");
                tableName = "";
                int i = 0;
                for (String table : tables) {
                    fromQuery.append(table);
                    fromQuery.append(" ");
                    fromQuery.append(table);
                    if (i != tables.size()) {
                        fromQuery.append(",");
                    } else {
                        fromQuery.append("");
                    }
                    i++;
                }
                from = fromQuery.toString().replaceAll(",$", "");
                queryMap.put("query", select + from);
            }
            //from = from+"ORDER BY "+orderbyColumn+" "+sort+" ";
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                closeConnection(connection, null, null);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    } else {
        System.out.println("Connection not Established. Please Contact Vendor");
    }
    return queryMap;// return the map/ list which  contains query and sory and display order
}    

第3步:结果查询
{query= SELECT purchase_order.po_number,purchase_order.placed_date,purchase_order.date_closed,purchase_order.scheduled_arrival_date,purchase_order_inventory.unit_cost,purchase_order_inventory.order_quantity,purchase_order_inventory.roll_number,purchase_order_inventory.rec_vendor_quantity,products.product_sku,products.et_conversion_unit_quantity,product_categories.product_category_name ,product_vendors.vendor_name FROM purchase_order purchase_order,purchase_order_inventory purchase_order_inventory,products products,product_categories product_categories,product_vendors product_vendors}

但这不是我想要的,请帮我构建我给出的查询。

2 个答案:

答案 0 :(得分:2)

两次查询

您需要进行两次查询:

  1. 查询已启用的字段
  2. 构建第二个查询字符串(您要以dinamically方式构建的字符串)
  3. 就是这样,因为SQL查询必须告诉在查询任何数据之前将包含哪些列。事实上,它将用于构建内部数据库查询计划,它是数据库电机用于检索和组织您询问的数据的方式。

    查询所有列

    只查询那些字段是否必要?你不能查询所有内容并使用相关数据吗?

    <强>加入

    查看更新后的问题我想你需要动态添加条件以正确连接表。我应该做的是有一个参考,告诉我当桌子存在时要添加什么样的记录。

    至少有两个选择:

    1. 基于存在的表对(例如:“如果存在A和B,则添加A.col1 = B.col2”)
    2. 根据现有表格(“如果B存在,则添加A.col1 = B.col2; A应该存在”
    3. 根据您的示例,我认为第二个选项更适合(并且易于实现)。

      所以我应该有一些静态Map<String, JoinInfo>,其中JoinInfo至少有:

      JoinInfo
      + conditionToAdd // by example "A.col1 = B.col2"
      + dependsOnTable // by example "A" to indicate that A must be present when B is present
      

      所以你可以使用:

      1. 该信息用于添加应该是的表格(例如:即使A没有选定的cols,也必须存在才能与B联接)
      2. 将conditionToAdd包含在where子句
      3. 无论如何......我觉得你遇到了很多麻烦。为什么这么有活力?

答案 1 :(得分:2)

你必须一步一步地接近这件事。

首先,您必须创建一个返回所有status='Y'

行的查询

然后,您将把COLUMN_NAME放入字符串列表中。

List<String> list = new List<String>();
while(rs.next()){
  list.add(rs.getString(columnNumber));
}

然后你必须循环List并动态生成你的第二个sql语句

String sqlSelect = "SELECT ";
String sqlFrom = " FROM SOME_OTHER_TABLE "
String sqlWhere = " WHERE SOME_CONDITION = 'SOME_VALUE' "

for(String x : list){
  sqlFrom += x +" , "+;
}
//here make sure that you remove the last comma from sqlFrom  because you will get an SQLException


String finalSql = sqlSelect + sqlFrom + sqlWhere ;