1. 程式人生 > >【Flask】Sqlalchemy join

【Flask】Sqlalchemy join

efault sql RM 條件 root creat self esc name

### 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

【Flask】Sqlalchemy join