2012-05-02 31 views
0

在测试(非web2py)程序中,我使用了一个调用SELECT SUBSTRING_INDEX的MySQL查询。在web2py的DAL规范中将其转换为正确用法的最简单方法是什么?转换MySQL查询以在web2py中使用DAL

查询如下:

http://pastie.textmate.org/3848916

SELECT SUBSTRING_INDEX(ipaddress, '.', 3) AS first_three_octet, count(*) AS ipCount, updated 
      FROM ips 
      GROUP BY SUBSTRING_INDEX(ipaddress, '.', 3) 
      HAVING ipCount = 254 
      ORDER BY ipCount DESC 

仅供参考 - 我kludged在一起这段代码在此期间来完成我需要:

def ListFullRanges(): 
    import re 
    f3o = '(\d{1,3}\.\d{1,3}\.\d{1,3})' 
    fullrange = [] 

    rg1 = re.compile(f3o,re.IGNORECASE|re.DOTALL) 
    for row in db(db.ips).select(): 
     m = rg1.findall(row.ipaddress) 
     if not m[0] in fullrange: 
      if db(db.ips.ipaddress.startswith(m[0])).count() == 254: 
       fullrange.append(m[0]) 
    print fullrange 

    return dict(fr=fullrange) 

回答

1

有时有像这些非常复杂的查询专为单个数据库引擎而制作。虽然不是“完美”的解决方案,您可以使用使用你已经建立的MySQL查询:

db.executesql(
     "SELECT SUBSTRING_INDEX(ipaddress, '.', 3) AS first_three_octet, count(*) AS ipCount, updated 
     FROM ips 
     GROUP BY SUBSTRING_INDEX(ipaddress, '.', 3) 
     HAVING ipCount = 254 
     ORDER BY ipCount DESC", as_dict=True 
) 

这将返回一个字典列表,这将是类似的,你会得到使用什么DAL查询。使用executableql也更快。唯一的缺点是,它可能只适用于MySQL,你不能在SQLFORM中使用它。但是如果你只是计划使用MySQL,那么这可能是最好的解决方案。