根据相关表更新HSQL表值

时间:2016-01-10 19:17:48

标签: sql libreoffice-base

我有两个相关的表:"大学"(id,num_courses)和"课程" (id,university_id)。我需要University.num_courses来代表COUNT个课程。

我可以查询我需要的数据:

SELECT 
Universities.id,
COUNT(Courses.university_id) as NumCourses
FROM Courses
JOIN Universities ON Universities.id = Courses.university_id
GROUP BY Universities.id

如何用它更新大学?可以自动完成吗?

1 个答案:

答案 0 :(得分:1)

我不确定这是“自动”的意思,但可以通过循环完成:

Sub UpdateUniversities
    Context = CreateUnoService("com.sun.star.sdb.DatabaseContext")
    databaseURLOrRegisteredName = "file:///C:/Users/JimStandard/Desktop/New Database.odb"
    Db = Context.getByName(databaseURLOrRegisteredName )
    Conn = Db.getConnection("","") 'username & password pair - HSQL default blank
    Stmt = Conn.createStatement()
    strSQL = "SELECT Universities.id, " & _
        "COUNT(Courses.university_id) as NumCourses " & _
        "FROM Courses " & _
        "JOIN Universities ON Universities.id = Courses.university_id " & _
        "GROUP BY Universities.id"
    oResult = Stmt.executeQuery(strSQL)
    Do While oResult.next()
        university_id = oResult.getLong(1)
        num_courses = oResult.getLong(2)
        Stmt = Conn.createStatement()
        strSQL = "UPDATE ""Universities"" SET ""num_courses"" = " & _
            num_courses & " WHERE ""id"" = " & university_id
        Stmt.executeUpdate(strSQL)
    Loop
    Conn.close()
End Sub

相关:How to create an update query with Open Office Base?