3

被 ORM 折磨, sql 1 分钟写好, ORM 想了一个小时,没写出来😭

 2 years ago
source link: https://www.v2ex.com/t/801777
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Python

被 ORM 折磨, sql 1 分钟写好, ORM 想了一个小时,没写出来😭

  wuwukai007 · 11 小时 46 分钟前 · 2743 次点击

救救孩子吧

select d.id,d.created_time,(select count(*) from word where word.dictionary_id=d.id)
    as word_count,
       (select account from user where user.id = d.creator_id) as username,
       d.dictionary_name
        from dictionary
    as d where d.thesaurus_name='professional'

第 1 条附言  ·  10 小时 47 分钟前

word_count = select(func.count(Word.id)).where(Word.dictionary_id==Dictionary.id).label('word_count') username = select(User.account).where(User.id == Dictionary.creator_id).as_scalar().label('username') s = select(Dictionary.created_time,word_count,username).where(Dictionary.thesaurus_name=='professional')

SELECT dictionary.created_time, (SELECT count(word.id) AS count_1 
FROM word 
WHERE word.dictionary_id = dictionary.id) AS word_count, (SELECT "user".account 
FROM "user" 
WHERE "user".id = dictionary.creator_id) AS username 
FROM dictionary 
WHERE dictionary.thesaurus_name = :thesaurus_name_1

第 2 条附言  ·  8 小时 27 分钟前

格式化一下

from sqlalchemy import select ,func
word_count = select(func.count(Word.id)).where(Word.dictionary_id==Dictionary.id).label('word_count')
username = select(User.account).where(User.id == Dictionary.creator_id).as_scalar().label('username')
sql = select(Dictionary.created_time,word_count,username).where(Dictionary.thesaurus_name=='professional')
print(s)
'''
SELECT dictionary.created_time, (SELECT count(word.id) AS count_1 
FROM word 
WHERE word.dictionary_id = dictionary.id) AS word_count, (SELECT "user".account 
FROM "user" 
WHERE "user".id = dictionary.creator_id) AS username 
FROM dictionary 
WHERE dictionary.thesaurus_name = :thesaurus_name_1
'''

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK