V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
smallgoogle
V2EX  ›  Python

sqlalchemy 语句如何进行拼接

  •  
  •   smallgoogle · 2019-05-11 23:15:28 +08:00 · 2581 次点击
    这是一个创建于 1782 天前的主题,其中的信息可能已经有所发展或是发生改变。
    array = [1,2,3,4,5]    #我的是一个数组,数量未知,我想实现下面的效果,怎么拼接呀?
    
    # func.find_in_set(1, cls.types)    就是把数组里的数字一个个的填入这里面,然后有多少就组合多少个;
    
    # 效果
    data = MysqlDB.session.query(cls).filter(
        and_(
            func.find_in_set(1, cls.types),
            func.find_in_set(2, cls.types),
            func.find_in_set(3, cls.types), 
            func.find_in_set(4, cls.types), 
            func.find_in_set(5, cls.types)
        )
    ).limit(limit).all()
    
    

    一天了都没拼接组合出来。实在没办法了。来问一下前辈们。

    其实我是想查询数据库,表结构
    id----types
    1----1,2,3
    2----7,8,9
    3----15,8,3
    4----17,2,5
    5----9,7,12

    假设我想查询 包含 2 和 5 的
    就会出现第 4 条数据。我测试了这个查询语句是可用的,并且准确的;
    可是现在就是不会组合拼接。
    因为我的查询给的 types 长度不一定,内容也不一定。

    8 条回复    2019-05-13 10:02:05 +08:00
    zhijiansha
        1
    zhijiansha  
       2019-05-11 23:45:35 +08:00
    [func.find_in_set(x, cls.types) x for x in array]
    把这个*list 放入 and_里?
    smallgoogle
        2
    smallgoogle  
    OP
       2019-05-12 00:54:33 +08:00
    @zhijiansha 额。不行。 = =这样是不行的。
    merpyzf
        3
    merpyzf  
       2019-05-12 01:47:41 +08:00 via iPhone
    @smallgoogle 我也是这么想的😂问题出在哪儿了?
    Eds1995
        4
    Eds1995  
       2019-05-12 09:28:47 +08:00 via Android
    试试 cls.types.in_(arrays)
    zhijiansha
        5
    zhijiansha  
       2019-05-12 09:29:30 +08:00 via iPhone
    @smallgoogle #2 是否加了*解包?
    billgreen1
        6
    billgreen1  
       2019-05-12 13:18:52 +08:00
    建议抽空看看 SQL 反模式第一部分第二章: 乱穿马路
    Linys
        7
    Linys  
       2019-05-12 16:23:19 +08:00
    不能换个写法吗
    data = MysqlDB.session.query(cls)

    for i in array:
    data = data.filter(func.find_in_set(i, cls.types))

    data = data.limit(limit).all()

    不知道这样行吗
    cassidyhere
        8
    cassidyhere  
       2019-05-13 10:02:05 +08:00
    func.find_in_set 的返回值需要是 sqlalchemy.sql.elements.BinaryExpression
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3102 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:53 · PVG 20:53 · LAX 05:53 · JFK 08:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.