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
eteryao
V2EX  ›  Python

萌新求助 ! Python sqlalchemy 的复杂写法。

  •  
  •   eteryao · 2019-07-15 10:38:35 +08:00 · 1800 次点击
    这是一个创建于 1719 天前的主题,其中的信息可能已经有所发展或是发生改变。
    大佬们 求助! 有没有 orm 写的很 6 的大佬!!!

    救救萌新!
    现有一条原生 sql。
    select a.date,sum(a.tag_count) as tag_count,a.tag_id,a.tag_name,b.user_id,b.user_name from (
    (

    select z.netflow_alias,count(1) as tag_count,z.date,z.product_id,x.tag_id,x.tag_name from
    (
    SELECT netflow_alias,left(create_time,10) as date,product_id FROM weidian_operator.t_tj_order_detail_qingshe
    where left(create_time,10)=DATE_SUB(curdate(),INTERVAL 1 DAY)
    ) z
    left join
    (

    select q.tag_id,q.product_id,w.tag_name from
    (SELECT tag_id,product_id FROM weidian_operator.t_product_tag ) q

    left join

    (select id,tag_name from weidian_operator.t_tag) w
    on q.tag_id=w.id

    ) x
    on z.product_id=x.product_id
    group by x.tag_id

    ) a

    left join

    (select netflow_alias,user_name,user_id from weidian_operator.t_tj_team_relation where user_id is not null) b

    on a.netflow_alias=b.netflow_alias
    )
    where user_id is not null
    group by a.date,b.user_id;

    那么请问 orm 怎么写。 哪位大佬肯帮帮我。呜呜呜
    8 条回复    2019-07-16 21:50:12 +08:00
    myyou
        1
    myyou  
       2019-07-15 10:41:38 +08:00
    orm 不适合或者写不了复杂的 SQL,你还是老老实实的直接用 SQL 查吧。
    eteryao
        2
    eteryao  
    OP
       2019-07-15 10:46:41 +08:00
    @myyou emmm 好的吧。谢谢大佬!!
    ipwx
        3
    ipwx  
       2019-07-15 10:57:20 +08:00
    我记得 SQLAlchemy 可以把 SQL 结果提取出来变成 object。
    vZexc0m
        4
    vZexc0m  
       2019-07-15 11:17:20 +08:00
    这么多子查询 抽出来不就简单了吗
    arrow8899
        5
    arrow8899  
       2019-07-15 11:28:43 +08:00
    1. 把子查询分开查,然后在程序里面做处理;
    2. 加索引,不要使用 Null ;
    3. 看能否优化你的数据模型,避免这种复杂的 join group 查询;
    4. 如果数据量小的话,估计还将就;对于大量数据来说,还是建议使用 Flink Spark 这种工具先聚合处理一次,避免重复在代码里面进行大量的 group join 以及函数运算操作,否则性能会很差。
    txy3000
        6
    txy3000  
       2019-07-15 13:02:26 +08:00
    先去看看业务逻辑吧 照着这个 sql 硬改事倍功半
    hp66722667
        7
    hp66722667  
       2019-07-15 17:15:50 +08:00
    这个排版真是头疼,一点看的欲望都没有
    lolizeppelin
        8
    lolizeppelin  
       2019-07-16 21:50:12 +08:00
    这种复杂查询,量小还好,量大没专门优化过,直接要死
    还拿 ORM 来做......
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5393 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 06:57 · PVG 14:57 · LAX 23:57 · JFK 02:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.