1

我有一个包含 companyID 和一些相关分数的表“分数”。companyID 可以在此表中出现多次。我有另一个包含公司 ID 和公司名称的表(“公司”)。我想要做的是查询“公司”表以获取所有公司 ID,然后使用此结果使用我之前查询的结果查询“分数”表以获取分数。我还需要做一些计算。我想我需要遍历第一个结果集并将 companyID 值放入我的第二个查询中。只是不知道该怎么做。任何帮助将不胜感激。

我知道这段代码行不通,但是它可能会让您了解我要完成的工作:

<cfquery name="companyIDs" datasource="myDB">
   Select companyID from company
</cfquery>

<cfloop>
 <cfquery name="companyScore" datasource="myDB">
 SELECT Round(sum(leadership)/Count(leadership)) as leadership,   
 Round(sum(communication)/Count(communication)) as communication, 
 Round(sum(fairness)/Count(fairness)) as fairness, 
 Round(sum(ethics)/Count(ethics)) as ethics, 
 Round(sum(competence)/Count(competence)) as competence 
 FROM scores 
 Where companyID = 'companyIDs.companyID'
 </cfquery>
</cfloop>

4

2 回答 2

4

有几种方法可以做到这一点,但下面的方法会起作用。

<cfquery name="companyIDs" datasource="myDB">
Select companyID from company
</cfquery>

<cfloop query="companyIDs">
 <cfquery name="companyScore" datasource="myDB">
 SELECT Round(sum(leadership)/Count(leadership)) as leadership,   
 Round(sum(communication)/Count(communication)) as communication, 
 Round(sum(fairness)/Count(fairness)) as fairness, 
 Round(sum(ethics)/Count(ethics)) as ethics, 
 Round(sum(competence)/Count(competence)) as competence 
 FROM scores 
 Where companyID = #companyIDs.companyID#
 </cfquery>
</cfloop>

您还可以将两个查询连接在一起,这样您就只有一个整体查询,这将是首选方式。

<cfquery name="companyScore" datasource="myDB">
 SELECT companyID,
 Round(sum(leadership)/Count(leadership)) as leadership,   
 Round(sum(communication)/Count(communication)) as communication, 
 Round(sum(fairness)/Count(fairness)) as fairness, 
 Round(sum(ethics)/Count(ethics)) as ethics, 
 Round(sum(competence)/Count(competence)) as competence 
 FROM scores INNER JOIN company ON scores.companyID = company.companyID
 GROUP BY companyID
 </cfquery>
于 2012-11-07T20:53:49.393 回答
0

有更好的方法来完成您的需求,但我按照您的要求回答了您的问题。我对您的代码进行了一些更改:

<cfloop query='companyIDs'> // add the name of your query to the cloop
 <cfquery name="companyScore" datasource="myDB">
 SELECT Round(sum(leadership)/Count(leadership)) as leadership,   
 Round(sum(communication)/Count(communication)) as communication, 
 Round(sum(fairness)/Count(fairness)) as fairness, 
 Round(sum(ethics)/Count(ethics)) as ethics, 
 Round(sum(competence)/Count(competence)) as competence 
 FROM scores 
 Where companyID = '#companyIDs.companyID#' // add ## around your output
 </cfquery>

<cfdump var='#companyScore#'>  // dump your results

</cfloop>
于 2012-11-07T20:57:12.833 回答