如何将多个“SELECT”语句合并为一个?

时间:2017-07-13 08:08:20

标签: java sql-server select

目前,我正在使用for循环,当orgList内部有数千个元素时,这会慢得令人无法接受:

String sql = "SELECT xua.XUAID, xua.XUA01, xua.XUA02 "
            + "FROM dbo.XDSysUseArea xua "
            + "WHERE xua.XUA03=?";

conn = ds.getConnection();
ps = conn.prepareStatement(sql);

for(HotelSource org : orgList) {
    ps.setString(1, org.getPrimaryKey());
    rs = ps.executeQuery();

    while (rs.next()) {
        // do sth
    }
}

执行SELECT的正确方法是什么?

4 个答案:

答案 0 :(得分:5)

您应该使用SQL SELECT ... FROM ... WHERE xua.XUA03 IN (x, y, z, ...) ,例如:

?

您仍然可以参数化您的查询,但您需要在语句中生成正确数量的String params = "?, ?, ?, ?"; //you will have to generate enough of these yourself //This is an exercise for you! String sql = "SELECT xua.XUAID, xua.XUA01, xua.XUA02 " + "FROM dbo.XDSysUseArea xua " + "WHERE xua.XUA03 IN (" + params + ")"; conn = ds.getConnection(); ps = conn.prepareStatement(sql); int index = 1; for(HotelSource org : orgList) { ps.setString(index, org.getPrimaryKey()); // ^^^^^ use index here index++; } rs = ps.executeQuery(); while (rs.next()) { // do sth } 。所以这里有一些伪代码,因为我不做Java:

orgList

注意:这样做的缺点是你提到你在If your data is: content = [1, 2, 3, ... , 100] Then write {% if content %} <div class="Parent"> {% for item in content %} <div class="child-wrapper">{{ item }}</div> {% endfor %} </div> {% endif %} If your data is array of assotiated arrays like this: content = [ ['content' => 1], ['content' => 2], ] Then write {% if content %} <div class="Parent"> {% for item in content %} <div class="child-wrapper">{{ item.content }}</div> {% endfor %} </div> {% endif %} 中有数千个条目,这使得使用这种方法变得非常糟糕。事实上,SQL Server不允许您使用超过几千个参数。

答案 1 :(得分:3)

使用IN运算符无需点击每个值的查询

SELECT xua.XUAID, xua.XUA01, xua.XUA02 
FROM dbo.XDSysUseArea xua 
WHERE xua.XUA03 in (val1,val2,val3,..) -- pass the list here

答案 2 :(得分:1)

将argylget List<Integer>中的org.getprimarkey()存储到where子句中使用in运算符 SELECT xua.XUAID, xua.XUA01, xua.XUA02 " + "FROM dbo.XDSysUseArea xua " + "WHERE xua.XUA03 IN (mylist);

注意:使用replaceall方法替换列表中的[]。

答案 3 :(得分:1)

您可以将操作符IN用于此目的。例如,

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);