【问题标题】:converting a MySQL query to use in web2py DAL将 MySQL 查询转换为在 web2py DAL 中使用
【发布时间】:2012-05-12 01:59:47
【问题描述】:

在一个测试(非 web2py)程序中,我正在使用一个调用 SELECT SUBSTRING_INDEX 的 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 

仅供参考 - 同时我已经将这段代码拼凑在一起以完成我需要的:

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)

【问题讨论】:

    标签: python mysql data-access-layer web2py


    【解决方案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 查询获得的结果。使用 executesql 也更快。唯一的缺点是它可能只适用于 MySQL,而您不能将它与 SQLFORM 一起使用。但如果您只打算使用 MySQL,那么这可能是最好的解决方案。

    【讨论】:

      猜你喜欢
      • 2014-05-06
      • 2012-02-22
      • 2013-07-17
      • 1970-01-01
      • 2015-07-19
      • 2013-03-08
      • 2018-11-07
      • 2019-07-29
      • 2018-11-01
      相关资源
      最近更新 更多