SQL查询仅返回ID6、7,需获取ID1、2、6、7,请求排查问题
问题分析与SQL修正
首先看你提供的原始数据和查询逻辑:
原始数据表内容:
ID Dst Channel destination 1 123 2 123 3 SIP/5raghami-00043236 91026 5 SIP/5raghami-00043232 91132 6 SIP/107-00043230 123 7 Local/123@from-queue-00006326;1 802
当前执行的SQL查询(仅返回ID6、7,预期返回ID1、2、6、7):
SQL = "SELECT id,duration FROM result where destination='123' or (destination='802' and [Dst Channel] like '%Local/123%')" RS.Open SQL, con while not rs.eof response.write rs("id") rs.movenext wend rs.close
你的疑问是ID1、2被忽略是否因为[Dst Channel]为空,或者括号使用问题——括号的使用是没问题的,问题出在查询条件没有覆盖到ID1、2的匹配规则。
从数据排版来看,ID1、2的Dst Channel字段值是123,而destination字段是空值;而你的查询只匹配了destination='123'的行(对应ID6)和destination='802'且Dst Channel包含Local/123的行(对应ID7),完全没包含Dst Channel='123'的情况,这就是ID1、2没被返回的原因。
如果你的预期是把以下三类行都返回:
destination等于123的行(ID6)Dst Channel等于123的行(ID1、2)destination等于802且Dst Channel包含Local/123的行(ID7)
那修正后的SQL应该加上[Dst Channel]='123'的条件:
SQL = "SELECT id,duration FROM result where destination='123' OR [Dst Channel]='123' OR (destination='802' and [Dst Channel] like '%Local/123%')"
如果你确实认为ID1、2的destination是123(可能是数据排版导致的误解),但查询没返回,那需要检查这两行的destination字段实际值:
- 是不是存为了
NULL?这种情况下需要把条件改成(destination='123' OR destination IS NULL) - 是不是字段值有多余空格?可以用
TRIM(destination)='123'来匹配 - 是不是数据库字段名大小写敏感?比如实际字段名是
Destination,而你写的是destination
内容的提问来源于stack exchange,提问作者Ali Sheikhpour
相关产品推荐
相关产品推荐

