Update HSQL table values based on related table

只愿长相守 提交于 2020-01-17 03:22:13

问题


I have 2 related tables: "Universities"(id, num_courses) and "Courses" (id, university_id). I need University.num_courses to represent a COUNT of courses.

I can query data I need:

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

How do I UPDATE Universities with it? Could it be done automatically?


回答1:


I am not sure this is what you mean by "automatically," but it can be done with a loop:

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

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



来源:https://stackoverflow.com/questions/34709741/update-hsql-table-values-based-on-related-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!