我有两个相关的表:"大学"(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
如何用它更新大学?可以自动完成吗?
答案 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