我有一个返回7条记录的查询:
<cfquery name="equip" datasource="#datasource#">
select equipment_id from service_ticket
where equipment_id > 0
</cfquery>
然后我接受这些结果并再次运行另一个查询:
<cfquery name="get_equipment_tally" datasource="#datasource#">
select *
from equipment_maintenance
where active = "yes" AND id <> #equip.equipment_id#
</cfquery>
但是查询“get_equipment_tally”只是将'id'与where子句中查询结果“equip”的第一条记录进行比较,即使返回了7条记录。
有办法吗?
答案 0 :(得分:2)
AND id NOT IN <cfqueryparam cfsqltype="cf_sql_integer"
value="#valueList(equip.equipment_id)#" list="true">
理想情况下,您可以通过
将其转换为一个查询<cfquery name="get_equipment_tally" datasource="#datasource#">
select *
from equipment_maintenance
where active = "yes" AND id NOT IN (select equipment_id from service_ticket where equipment_id > 0)
</cfquery>
答案 1 :(得分:0)
我喜欢这些答案,但在查询中看到NOT IN会让我抽搐。使用LEFT OUTER JOIN ... IS NULL。它会更快。
SELECT <list of cols here>
FROM equipment_maintenance em
LEFT OUTER JOIN equipment_id ei ON ei.equipment_id = em.equipment_id
WHERE em.Active = 'yes'
AND ei.equipment_id IS NULL
类似的东西。