关联查询 join的使用
Posted 失落的黎明
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关联查询 join的使用相关的知识,希望对你有一定的参考价值。
1 #!/usr/bin/env python 2 import sqlalchemy 3 from sqlalchemy import create_engine 4 from sqlalchemy.ext.declarative import declarative_base 5 from sqlalchemy import Column, Integer, String,ForeignKey 6 from sqlalchemy.orm import sessionmaker,relationship 7 print(sqlalchemy.__version__) 8 9 engine = create_engine(‘mysql+pymysql://root:[email protected]:3306/a1‘,echo = True) 10 11 Base = declarative_base(engine) 12 13 class Father(Base): 14 __tablename__ = "father" 15 16 id = Column(Integer,autoincrement=True,primary_key=True) 17 name = Column(String(20)) 18 son = relationship(‘Father‘) 19 def __repr__(self): 20 return self.name 21 22 class Son(Base): 23 __tablename__ = ‘son‘ 24 id = Column(Integer,autoincrement=True,primary_key=True) 25 name = Column(String(20)) 26 email = Column(String(20)) 27 father_id = Column(Integer,ForeignKey(‘father.id‘)) 28 Base.metadata.create_all(engine) 29 30 Session = sessionmaker(bind=engine) 31 session = Session() 32 # f1 = Father(name = "fafafa") 33 # session.add(f1) 34 # s1 = Son(name = ‘sq‘,email = ‘@qq.com‘,father_id = 1) 35 # s2 = Son(name = ‘sw‘, email= ‘[email protected]‘,father_id= 1) 36 # session.add_all([s1,s2]) 37 38 39 ret = session.query(Father.name,Son.name).join(Son).first() 40 print("ret=",ret) 41 session.commit()
以上是关于关联查询 join的使用的主要内容,如果未能解决你的问题,请参考以下文章