sqlalchemy的join使用
——、先看mysql的join链接方法
#encoding: utf-8 from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,Enum,\
ForeignKey,DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,relationship
from random import randint
from datetime import datetime
HOSTNAME = '127.0.0.1' PORT = 3306 DATABASE = 'first_sqlalchemy' USERNAME = 'root' PASSWORD = '' #dialect+driver://username:password@host:port/database
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" \
"{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base = declarative_base(engine) # Session = sessionmaker(engine)
# session = Session() session = sessionmaker(engine)() #Session(**local_kw) class User(Base):
__tablename__ = 'user'
id = Column(Integer,primary_key=True,autoincrement=True)
username = Column(String(32),nullable=False) # articles = relationship("Article") #获取用户发布所有文章
def __repr__(self):
return '<User:%s>'%self.username class Article(Base):
__tablename__ = 'article'
id = Column(Integer,primary_key=True,autoincrement=True)
title = Column(String(50),nullable=False)
create_time = Column(DateTime,default=datetime.now)
uid = Column(Integer,ForeignKey('user.id',ondelete='RESTRICT'))
author = relationship('User',backref='articles') #sqlalchemy orm提供的 def __repr__(self):
return '<Article:%s>'%self.title # Base.metadata.drop_all()
#
# Base.metadata.create_all()
#
# user1 = User(username='zhiliao')
# user2 = User(username='ketang')
#
# for x in range(1):
# article = Article(title='title%s'%x)
# article.author = user1
# session.add(article)
# session.commit()
#
#
# for x in range(1,3):
# article = Article(title='title%s'%x)
# article.author = user2
# session.add(article)
# session.commit() #找到所有的用户,根据文章的数量进行排序 result = session.query(User.username,func.count(Article.id)).join(Article,User.id==Article.uid).\
group_by(User.id).order_by(func.count(Article.id).desc()).all()
print(result)#[('ketang', 2), ('zhiliao', 1)] '''
SELECT user.username AS user_username, count(article.id) AS count_1
FROM user INNER JOIN article ON user.id = article.uid GROUP BY user.id ORDER BY count(article.id)
'''
sqlalchemy的join使用的更多相关文章
- 四十四:数据库之SQLAlchemy之join实现复杂查询
准备工作 from datetime import datetime from sqlalchemy import create_engine, Column, Integer, String, Da ...
- SQLAlchemy(2):多表操作 & 连接方式及原生SQL
一对多:ForeignKey multitb_models.py import datetime from sqlalchemy import create_engine # 引入 创建引擎 from ...
- SQLALlchemy数据查询小集合
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作.将对象转换成SQL,然后使用数据API执行SQL并获取执行结果.在写项目的过 ...
- Flask-SQLAlchemy 与 SQL Alchemy 的区别、联系
目录 一.SQL Alchemy 1. SQL Alchemy 基本操作 1.1 连接数据库 1.2 声明映射(建立数据库表的模型) 1.3 创建映射类的实例 1.4 创建会话 1.5 单表的增删改查 ...
- SQLAlchemy高级ORM之改查删除及GROUP,JOIN...
按书上案例来的. #coding=utf-8 from datetime import datetime from sqlalchemy import (MetaData, Table, Column ...
- SQLAlchemy增删改查基本操作,及SQL基本技能样码(join,group)
练了一天,基本的东东应该有感觉了. #coding=utf-8 from datetime import datetime from sqlalchemy import (MetaData, Tabl ...
- 【Flask】Sqlalchemy join
### join:1. join分为left join(左外连接)和right join(右外连接)以及内连接(等值连接).2. 参考的网页:http://www.jb51.net/article/1 ...
- Superset安装出错 sqlalchemy.exc.InvalidRequestError: Can't determine which FROM clause to join from, ...
$ superset db upgrade ... Traceback (most recent call last): File "/home/jhadmin/.pyenv/version ...
- sqlalchemy多表联合查询(join)
使用outerjoin instances = db.session.query(Instance.name, Instance.sep_status, User.email).outerjoin( ...
随机推荐
- sql 查询列
select 'A' AS A , B ='B'
- C#与数据库有关的控件和属性
BindingNavigator 数据记录导航 BindingSource 与数据源绑定, 常用属性:DataSource.DataMember 常用方法: DataGridView 以表格形式显示 ...
- UI案例
<Window x:Class="WpfDemo2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/20 ...
- 【Python网络】HTTP
HTTP概述 HTTP(hypertext transport protocol),即超文本传输协议.这个协议详细规定了浏览器和万维网服务器之间互相通信的规则. HTTP就是一个通信规则,通信规则规定 ...
- java上传超大文件解决方案
用JAVA实现大文件上传及显示进度信息 ---解析HTTP MultiPart协议 (本文提供全部源码下载,请访问 https://github.com/1269085759/up6-jsp-mysq ...
- 【CUDA 基础】4.3 内存访问模式
title: [CUDA 基础]4.3 内存访问模式 categories: - CUDA - Freshman tags: - 内存访问模式 - 对齐 - 合并 - 缓存 - 结构体数组 - 数组结 ...
- ArrayList,LinkedList和String
import java.util.ArrayList; public class Demo{ public static void main(String[] args) throws Excepti ...
- vfprintf()函数
函数声明:int vfprintf(FILE *stream, const char *format, va_list arg) 函数参数: stream—这是指向了FILE对象的指针,该FILE对象 ...
- http1.1管线话 vs htttp2.0 多路复用
图中第一种请求方式,就是单次发送request请求,收到response后再进行下一次请求,显示是很低效的. 于是http1.1提出了管线化(pipelining)技术,就是如图中第二中请求方式,一次 ...
- sklearn4_混合分类器
python机器学习-乳腺癌细胞挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003&u ...