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

1. sql 写不出来了 2. 如何将这个 sql 翻译成 sqlalchemy 语句...

  •  
  •   chaleaochexist · 2019-01-14 17:38:33 +08:00 · 1853 次点击
    这是一个创建于 1900 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请教问题.

    1. 表 django_info.auth_user 有 id, name 和 age
    2. fd_group 有 id, fabric_name, role 其中 fabric_name + role 组成一个唯一约束
    3. fd_users_groups_m2m 关联表

    现在想查询 不在 fabric_name = 'default' 中的所有 user

    这么写没毛病吧? 还有其他方式吗?

    SELECT *
    FROM django_info.auth_user 
    LEFT OUTER JOIN (
        fd_users_groups_m2m AS fd_users_groups_m2m_1 
        INNER JOIN fd_group AS fd_group_1 
        ON fd_group_1.id = fd_users_groups_m2m_1.fd_group_id
        where fd_group_1.fabric_name != 'default') 
    ON django_info.auth_user.id = fd_users_groups_m2m_1.fd_user_id
    
    chaleaochexist
        1
    chaleaochexist  
    OP
       2019-01-14 18:26:20 +08:00
    ```
    SELECT "posts_user"."id", "posts_user"."name"
    FROM "posts_user"
    WHERE NOT (
    "posts_user"."id" IN (
    SELECT U1."user_id" AS Col1
    FROM "posts_user_group" U1
    INNER JOIN "posts_group" U2
    ON (U1."group_id" = U2."id")
    WHERE U2."title" = 1)
    )
    ```
    chaleaochexist
        2
    chaleaochexist  
    OP
       2019-01-14 18:26:35 +08:00
    但是如何翻译成 sqlalchemy...
    Hanayok
        3
    Hanayok  
       2019-01-14 18:57:58 +08:00
    如果你的 m2m 字段写在 auth 表的话就这样
    django_info.auth_user.objects.exclude(fd_group__fabric_name='default').all()
    xuanbg
        4
    xuanbg  
       2019-01-15 07:32:09 +08:00
    select u.*
    from django_info.auth_user u
    join fd_users_groups_m2m r on r.user_id = i.id
    join fd_group g on g.id = r.group_id
    and g. fabric_name = 'default';
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5392 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 07:47 · PVG 15:47 · LAX 00:47 · JFK 03:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.