【Flask】Sqlalchemy join

酆华皓
2023-12-01

### join:
1. join分为left join(左外连接)和right join(右外连接)以及内连接(等值连接)。
2. 参考的网页:http://www.jb51.net/article/15386.htm
3. 在sqlalchemy中,使用join来完成内连接。在写join的时候,如果不写join的条件,那么默认将使用外键来作为条件连接。
4. query查找出来什么值,不会取决于join后面的东西,而是取决于query方法中传了什么参数。就跟原生sql中的select 后面那一个一样。
比如现在要实现一个功能,要查找所有用户,按照发表文章的数量来进行排序。示例代码如下:

 

 1 # coding:utf-8
 2 # Author: liangjun.chen
 3 
 4 from datetime import datetime
 5 from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, ForeignKey, func
 6 
 7 from sqlalchemy.ext.declarative import declarative_base
 8 from sqlalchemy.orm import sessionmaker, relationship, backref
 9 
10 HOSTNAME = '127.0.0.1'
11 PORT = 3306
12 DATABASE = 'sqlalchemy_first'
13 USERNAME = 'root'
14 PASSWORD = '123456'
15 
16 DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{dbname}?charset=utf8'.format(
17         username=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, dbname=DATABASE
18 )
19 engine = create_engine(DB_URI)
20 Base = declarative_base(engine)
21 Session = sessionmaker(engine)
22 session = Session()
23 
24 
25 # article
26 class Article(Base):
27     __tablename__ = 'article'
28     id = Column(Integer, primary_key=True, autoincrement=True)
29     title = Column(String(50), nullable=False)
30     create_time = Column(DateTime,nullable=False, default=datetime.now)
31     uid = Column(Integer, ForeignKey("user.id"))
32 
33     # relation 正向引用, backref反向引用
34     author = relationship("User", backref=backref('articles', lazy='dynamic'))
35 
36     def __repr__(self):
37         return "Article <title: {}>".format(self.title)
38 
39 
40 class User(Base):
41     __tablename__ = 'user'
42     id = Column(Integer, primary_key=True, autoincrement=True)
43     username = Column(String(50), nullable=False)
44 
45 
46 # Base.metadata.drop_all()
47 # Base.metadata.create_all()
48 #
49 # user1 = User(username='saber')
50 # user2 = User(username='slamdunk')
51 #
52 #
53 # for _ in xrange(1):
54 #     article = Article(title='article{}'.format(_))
55 #     article.author = user1
56 #     session.add(article)
57 # session.commit()
58 #
59 # for _ in xrange(3):
60 #     article = Article(title='article{}'.format(_))
61 #     article.author = user2
62 #     session.add(article)
63 # session.commit()
64 
65 # 找到所有用户, 按照发表文章数量进行排序
66 
67 result = session.query(User.username, func.count(Article.id)).join(Article, Article.uid==User.id).group_by(User.id).order_by(func.count(Article.id).desc()).all()
68 print result

 

转载于:https://www.cnblogs.com/chen0427/p/8799237.html

 类似资料: