Forty-three: group_by SQLAlchemy of the database and having clauses

 

group_by: according to a field grouping, such as want to be grouped according to age, then count each group how many people
having: further filtering of search results, similar to where SQL statements

Ready to work

Import create_engine SQLAlchemy from, the Column, Integer, String, the Float, the Text, a ForeignKey, the DateTime, the Enum 
from sqlalchemy.ext.declarative Import declarative_base
from sqlalchemy.orm Import sessionmaker, Relationship, backref

# database information
Host = '127.0.0.1'
Port = '3306'
database = 'db_to_sqlalchemy'
username = 'the root'
password = '123456'

widget database # + type connection to the database, pymysql used herein
DB_URI = f'mysql + pymysql: // { username}: {password} @ { Host}: {Port} / {Database} '

engine = create_engine (DB_URI) # creation engine
base = declarative_base (engine) # use declarative_base create a base class
the session = sessionmaker (engine) ()


class the User (base):
__tablename__ =' User '
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False)
age = Column(Integer, default=0)
gender = Column(String(20), default='male')


Base.metadata.drop_all() # 删除所有表
Base.metadata.create_all() # 创建表

user1 = User(username='user1', age=20, gender='male')
user2 = User(username='user2', age=21, gender='female')
user3 = User(username='user3', age=20, gender='secret')
user4 = User(username='user4', age=26, gender='male')
user5 = User(username='user5', age=19, gender='female')
session.add_all([user1, user2, user3, user4, user5])
session.commit()

 

group_by: The data are grouped according to specific fields, such as: according to age group, the number of statistics for each group

Look at the transformation of SQL statements

The query returns data

 

HAVING: returns the data to the secondary filter, similar to where, as: age group, the number of statistics for each group, and then delete the selected data older than 25

Look at the transformation of SQL statements

The query returns data

 

Guess you like

Origin www.cnblogs.com/zhongyehai/p/11828337.html