WITH RECURSIVE dates AS ( SELECT "2021-12-01" AS date UNION ALL SELECT date + INTERVAL 1 DAY FROM dates WHERE date < "2023-03-27" ) SELECT DATE_FORMAT(dates.date, '%Y-%m-%d') AS date, IFNULL(COUNT(skins_logs.created_at), 0) AS count FROM dates LEFT JOIN skins_logs ON DATE(skins_logs.created_at) = dates.date AND skins_logs.skins_id = 481 WHERE dates.date BETWEEN "2021-12-01" AND "2023-03-27" GROUP BY dates.date;
时间: 2024-03-14 22:43:15 浏览: 100
如果您使用Flask和SQLAlchemy,可以使用以下代码将该查询转换为SQLAlchemy的查询:
```python
from datetime import datetime, timedelta
from sqlalchemy import func
from yourapp import db
class SkinLog(db.Model):
__tablename__ = 'skins_logs'
id = db.Column(db.Integer, primary_key=True)
skins_id = db.Column(db.Integer, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
start_date = datetime(2021, 12, 1).date()
end_date = datetime(2023, 3, 27).date()
dates = db.session.query(
func.date_union(start_date, end_date, interval=1),
func.date_format(func.date_union(start_date, end_date, interval=1), '%Y-%m-%d')
).subquery()
counts = db.session.query(
dates.c.date.label('date'),
func.ifnull(func.count(SkinLog.created_at), 0).label('count')
).outerjoin(
SkinLog,
func.date(SkinLog.created_at) == dates.c.date,
).filter(
SkinLog.skins_id == 481,
dates.c.date.between(start_date, end_date),
).group_by(
dates.c.date
).all()
```
这里首先定义了SkinLog模型类来映射skins_logs表。然后根据查询语句中的日期序列生成方式,使用SQLAlchemy的date_union函数生成日期序列。然后将日期序列与SkinLog表进行左连接,并按日期分组计算每个日期在SkinLog表中的记录数。最后使用filter来过滤出与skins_id为481相关的记录,并在查询结果中使用ifnull函数将没有记录的日期的记录数设置为0。最后使用all方法执行查询并返回结果。
阅读全文