1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import relationship
engine = create_engine('sqlite:///join_demo.db') Session = sessionmaker(bind=engine) session = Session()
Base = declarative_base()
class Table1(Base): __tablename__ = 'table1' id = Column(Integer, primary_key=True) name = Column(String) table2_rows = relationship("Table2")
class Table2(Base): __tablename__ = 'table2' id = Column(Integer, primary_key=True) table1_id = Column(Integer, ForeignKey('table1.id')) name = Column(String)
Base.metadata.create_all(engine)
table1_data = [ Table1(id=1, name='Table1 Row 1'), Table1(id=2, name='Table1 Row 2'), Table1(id=3, name='Table1 Row 3') ] session.bulk_save_objects(table1_data)
table2_data = [ Table2(id=1, table1_id=1, name='Table2 Row 1'), Table2(id=2, table1_id=3, name='Table2 Row 2') ] session.bulk_save_objects(table2_data)
inner_join_query = session.query(Table1, Table2).join(Table2, Table1.id == Table2.table1_id) inner_join_results = inner_join_query.all() print("Inner Join Results:") for result in inner_join_results: print(result[0].name, result[1].name) print()
left_join_query = session.query(Table1, Table2).join(Table2, Table1.id == Table2.table1_id, isouter=True) left_join_results = left_join_query.all() print("Left Join Results:") for result in left_join_results: print(result[0].name, result[1].name if result[1] else "NULL") print()
right_join_query = session.query(Table1, Table2).join(Table2, Table1.id == Table2.table1_id, isouter=True).from_statement("RIGHT JOIN table1 ON table1.id = table2.table1_id") right_join_results = right_join_query.all() print("Right Join Results:") for result in right_join_results: print(result[0].name if result[0] else "NULL", result[1].name) print()
full_join_query = session.query(Table1, Table2).join(Table2, Table1.id == Table2.table1_id, full=True) full_join_results = full_join_query.all() print("Full Join Results:") for result in full_join_results: print(result[0].name if result[0] else "NULL", result[1].name if result[1] else "NULL") print()
cross_join_query = session.query(Table1, Table2).cross_join(Table2) cross_join_results = cross_join_query.all() print("Cross Join Results:") for result in cross_join_results: print(result[0].name, result[1].name)
|