2012-05-02 16 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,那麼這可能是最好的解決方案。