四十四:数据库之SQLAlchemy之join实现复杂查询
Posted 向前走。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了四十四:数据库之SQLAlchemy之join实现复杂查询相关的知识,希望对你有一定的参考价值。
准备工作
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# 数据库信息
host = \'127.0.0.1\'
port = \'3306\'
database = \'db_to_sqlalchemy\'
username = \'root\'
password = \'123456\'
# 数据库类型+连接数据库的插件,这里使用的pymysql
DB_URI = f\'mysql+pymysql://{username}:{password}@{host}:{port}/{database}\'
engine = create_engine(DB_URI) # 创建引擎
Base = declarative_base(engine) # 使用declarative_base创建基类
session = sessionmaker(engine)()
class User(Base):
__tablename__ = \'user\'
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False)
def __repr__(self):
return f\'username: {self.username}\'
class Article(Base):
__tablename__ = \'article\'
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), nullable=False)
create_time = Column(DateTime, nullable=False, default=datetime.now)
uid = Column(Integer, ForeignKey(\'user.id\'))
author = relationship(\'User\', backref=\'article\')
def __repr__(self):
return f\'title: {self.title}\'
Base.metadata.drop_all() # 删除所有表
Base.metadata.create_all() # 创建表
user1 = User(username=\'user1\')
for x in range(1):
article = Article(title=f\'title{x}\')
article.author = user1
session.add(article)
session.commit()
user2 = User(username=\'user2\')
for x in range(1, 3):
article = Article(title=f\'title{x}\')
article.author = user2
session.add(article)
session.commit()
找到所有用户,按照文章数量进行排序
SQL语句实现
SQLAlchemy实现
由于已经使用了外建,所以会自动将User.id与Article.uid关联
以上是关于四十四:数据库之SQLAlchemy之join实现复杂查询的主要内容,如果未能解决你的问题,请参考以下文章
四十三:数据库之SQLAlchemy之group_by和having子句