四十四:数据库之SQLAlchemy之join实现复杂查询
时间:2021-07-01 10:21:17
帮助过:13人阅读
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKeyfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmaker, relationship# 数据库信息host = ‘127.0.0.1‘port = ‘3306‘database = ‘db_to_sqlalchemy‘username = ‘root‘password = ‘123456‘# 数据库类型+连接数据库的插件,这里使用的pymysqlDB_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实现复杂查询
标签:time 有用 col size elf 准备工作 ret 删除 alc