0

我有几张桌子。我也有疑问。我的问题是使用 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 

更新 :

询问 :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
}    

STEP 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}

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

4

2 回答 2

2

两个查询

您需要进行两个查询:

  1. 查询启用了哪些字段
  2. 构建第二个查询字符串(你想要动态构建的那个)

之所以这样,是因为 SQL 查询必须在查询任何数据之前告知将包含哪些列。事实上,它将用于构建内部 DB 查询计划,即 DB 电机将用于检索和组织您询问的数据的方式。

查询所有列

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

加入

查看更新的问题,我猜您需要动态添加 where 条件才能正确连接表。我应该做的是有一个参考告诉我当有桌子时要添加什么组合。

至少有两种选择:

  1. 基于存在的表对(例如:“如果存在 A 和 B,则添加 A.col1 = B.col2”)
  2. 基于存在的表(“如果存在 B,则添加 A.col1 = B.col2;A 应该存在”

根据您的示例,我认为第二个选项更合适(并且易于实施)。

所以我应该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 没有选定的列,也必须存在才能与 B 连接)
  2. 将 conditionToAdd 包含到 where 子句中

无论如何...我认为您遇到了很多麻烦。为什么这么有活力?

于 2012-09-12T07:28:31.937 回答
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 ;
于 2012-09-12T07:38:00.293 回答