【问题标题】:Java SQL update one table dynamically from another without idJava SQL 从另一个没有 id 的表动态更新一个表
【发布时间】:2015-08-15 03:53:20
【问题描述】:

我有两张这样的桌子:

Table 1:
Description -- Price 
Apple          10      
Wine           20       
Coffe          5        

Table 2:
Description -- Price -- Number
Pineapple       25       1
Coke            5        1
Orange Juice    8        2
Milk            10       3

我希望表 1 看起来像这样 ():

Description -- Price 
Pineapple       25      
Coke            5       
Orange Juice    8     
Milk            10   

我已经尝试过了,但我只得到了选择查询返回的最后一个值(导致所有行都具有相同的值)。

PreparedStatement ps = con.prepareStatement("update Table1 set Description=?, Price=? WHERE  (DATEPART(year, date) = "+arraydate[0]+"\n"+ 
                                    "AND    DATEPART(month, date) ="+arraydate[1]+"\n"+
                                    "AND    DATEPART(day, date) ="+arraydate[2]+")"); 
try {
      st=con.createStatement();
      ResultSet rs= st.executeQuery("select Description,Price from Table2 where number in(35,36)");
      while(rs.next()){
           String desc=rs4.getString("Description");
           Double price=rs4.getDouble("Price");

           ps.clearParameters();
           ps.setString(1,desc);
           ps.setDouble(2,price);
           ps.executeUpdate();
           }
      }
    catch(Exception ex)
  {ex.printStackTrace();}

谁能帮忙?非常感谢。

【问题讨论】:

  • 我猜问题是您的更新会影响多行。这看起来真的很臭。这些表是如何关联的?他们不是以某种方式联系在一起吗?

标签: java sql sql-server-2008 sql-update


【解决方案1】:

不确定您实际上要做什么..但是更新一个表基础而不是另一个很容易:

Update A
    Set A.Price = B.Price 
FROM Table1 as A
    INNER JOIN Table2 AS B
        ON A.Name = B.Name
        and A.Description = B.Description

如果这不能回答您的问题,请举例说明您期望这两个表在查询前后的样子。

【讨论】:

  • 这有帮助,谢谢。这是我第一次使用如此庞大的数据库,所以我没有意识到它还有第三个表与这两个表相关...抱歉打扰,再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多