Using Joins
Effect of joining is achieved by just placing two tables in either the columns clause or the Where clause of the select() construct. Now we use the join() and outerjoin() methods. The join() method returns a join object from one table object to another:
- join(right, onclause = None, isouter = False, full = False)
For example, following use of join() method will automatically result in join based on the foreign key:
You can explicitly mention joining criteria as follows:
If we now build the below select construct using this join as:
If this statement is executed using the connection representing engine, data belonging to selected columns will be displayed. The complete code is as follows:
- demo10.py
- #!/usr/bin/env python36
- from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
- from sqlalchemy import join
- from sqlalchemy.sql import select
- db_string = "postgresql://postgres:<password≷
@localhost/testdb" - engine = create_engine(db_string, echo = True)
- meta = MetaData(bind=engine)
- meta.reflect()
- conn = engine.connect()
- students = meta.tables['students']
- addresses = meta.tables['addresses']
- j = students.join(addresses, students.c.id == addresses.c.st_id)
- stmt = select([students, addresses.c.email_add]).select_from(j)
- result = conn.execute(stmt)
- for row in result.fetchall():
- print(row)
Using Conjunctions
Conjunctions are functions in SQLAlchemy module that implement relational operators used in WHERE clause of SQL expressions. The operators AND, OR, NOT, etc., are used to form a compound expression combining two individual logical expressions. A simple example of using AND in SELECT statement is as follows:
- SELECT * from EMPLOYEE WHERE salary>10000 AND age>30
and_() function
It produces a conjunction of expressions joined by AND. An example is given below for better understanding:
- from sqlalchemy import and_
- print(
- and_(
- students.c.name == 'Ravi',
- students.c.id <3
- )
- )
To use and_() in a select() construct on a students table, use the following line of code:
The complete code that displays output of the above SELECT query is as follows:
- demo11.py
- #!/usr/bin/env python36
- from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
- from sqlalchemy import join, and_, or_
- from sqlalchemy.sql import select
- db_string = "postgresql://postgres:
<password≷@localhost/testdb" - engine = create_engine(db_string, echo = True)
- meta = MetaData(bind=engine)
- meta.reflect()
- conn = engine.connect()
- students = meta.tables['students']
- addresses = meta.tables['addresses']
- stmt = select([students]).where(and_(students.c.name == 'Ravi', students.c.id <3))
- result = conn.execute(stmt)
- for row in result:
- print(row)
It produces conjunction of expressions joined by OR. We shall replace the stmt object in the above example with the following one using or_():
asc() function
It produces an ascending ORDER BY clause. The function takes the column to apply the function as a parameter:
- from sqlalchemy import asc
- stmt = select([students]).order_by(asc(students.c.name))
- SELECT students.id,
- students.name,
- students.lastname
- FROM students
- ORDER BY students.name ASC
- demo12.py
- #!/usr/bin/env python36
- from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
- from sqlalchemy import join, and_, or_, asc
- from sqlalchemy.sql import select
- db_string = "postgresql://postgres:
@localhost/testdb" - engine = create_engine(db_string, echo = True)
- meta = MetaData(bind=engine)
- meta.reflect()
- conn = engine.connect()
- students = meta.tables['students']
- addresses = meta.tables['addresses']
- from sqlalchemy import asc
- stmt = select([students]).order_by(asc(students.c.name))
- result = conn.execute(stmt)
- for row in result:
- print (row)
desc() function
Similarly desc() function produces descending ORDER BY clause as follows:
- from sqlalchemy import desc
- stmt = select([students]).order_by(desc(students.c.lastname))
- SELECT students.id,
- students.name,
- students.lastname
- FROM students
- ORDER BY students.lastname DESC
It produces a BETWEEN predicate clause. This is generally used to validate if value of a certain column falls between a range. For example, following code selects rows for which id column is between 2 and 4:
- from sqlalchemy import between
- stmt = select([students]).where(between(students.c.id,2,4))
- print (stmt)
- SELECT students.id,
- students.name,
- students.lastname
- FROM students
- WHERE students.id
- BETWEEN :id_1 AND :id_2
Supplement
* SQLAlchemy Cheetsheet
* Tutorialspoint - PostgreSQL - JOINS
沒有留言:
張貼留言