问题
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