简体   繁体   中英

Converting SQL statement to equivalent SQLAlchemy

I have the following SQL query (MySQL database)

SELECT distinct filename, DATE(created) 
  FROM FileTable 
 WHERE created > DATE_SUB(NOW(), INTERVAL 7 DAY);

My table definition:

**FileTable**
      id  : PK
filename  :varchar        
created   :date     

How to write an equivalent SQLAlchemy query for the above SQL statement and fetch results?

I tried this

myvar=session.query(FileTable).filter(created > DATE_SUB(NOW(), INTERVAL 7 DAY)).first()
return x.filename,x.DATE(created) for x in myvar

But it says the syntax is invalid. Please help. Thanks and regards :)

I suggest you are looking for magic func of sqlalchemy.sql.functions . Here is an example:

from sqlalchemy import *
metadata = MetaData()
FileTable = Table(
    'FileTable',
    metadata,
    Column('id', Integer, primary_key=True),
    Column('filename', String),
    Column('created', DateTime))

print select([
    distinct(FileTable.columns.filename),
    func.date(FileTable.columns.created)
]).where(
    FileTable.columns.created > func.date_sub(func.now(), 7))

# Output:
# SELECT DISTINCT "FileTable".filename, date("FileTable".created) AS date_1 
# FROM "FileTable" 
# WHERE "FileTable".created > date_sub(now(), :date_sub_1)

You can try this but it may results the rows those filenames are distinct in each dates(I've tested in PostgreSQL).

query = session.query(FileTable.filename.distinct(),
                      func.date(FileTable.created))\
               .filter(created > func.adddate(func.now(), -7))
return query.all()

If you find yourself wanting to retrieve only single row per single filename then you can transform query to fetch filenames and its (in example) latest created times like below:

query = session.query(FileTable.filename,
                      func.date(func.max(FileTable.created)))\
               .filter(created > func.adddate(func.now(), -7))\
               .group_by(FileTable.filename)
return query.all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM