#按用户名摸糊查询
trans_details.query.join(Uses).filter(Users.username.like('%xx%'))
#select xxx from trans_details inner join trans_details on users.id=trans_details.user_id where users.username like '%xx%'
#左外联接(left join)
trans_details.query.outerjoin(Uses).filter(Users.username.like('%xx%'))
#select xxx from trans_details left outer join trans_details on users.id=trans_details.user_id where users.username like '%xx%'
#以上是已经设置好外键,它自动找到关联的字段.也可以自己指定:
trans_details.query.join(Uses,trans_details.user_id==Users.id).filter(Users.username.like('%xx%'))
#select xxx from trans_details inner join trans_details on users.id=trans_details.user_id where users.username like '%xx%'
#另外一个更复杂的例子:
q=db.session.query(Credit_bills_details.no,Credit_bills_details.amount,Cards.no).outerjoin(Card_trans_details,
Credit_bills_details.no==Card_trans_details.trans_no).join(Cards,Card_trans_details.to_card_id==Cards.id)
.filter(Credit_bills_details.credit_bill_id==3)
#SELECT credit_bills_details.no AS credit_bills_details_no, credit_bills_details.amount AS credit_bills_details_amount, cards.no AS cards_no
# FROM credit_bills_details LEFT OUTER JOIN card_trans_details ON credit_bills_details.no = card_trans_details.trans_no INNER JOIN cards
# ON card_trans_details.to_card_id = cards.id WHERE credit_bills_details.credit_bill_id = %s
附录:
SQl内,外,左,右,全连接
表结构:
student
no |
name |
1 |
a |
2 |
b |
3 |
c |
4 |
d |
grade
no |
grade |
1 |
90 |
2 |
80 |
3 |
85 |
3 |
95 |
运行语句如下
select * from student,grade WHERE student.no = grade.no ---普通的where语句
select * from student inner join grade on student.no = grade.no ---内连接语句
select * from student left join grade on student.no = grade.no ---左连接语句
select * from student right join grade on student.no = grade.no ---右连接语句
select * from student full join grade on student.no = grade.no ---全连接语句
运行结果如下:
普通的where语句
no name no grade
1 a 1 90
2 b 2 80
3 c 3 85
3 c 3 90
内连接语句
no name no grade
1 a 1 90
2 b 2 80
3 c 3 85
3 c 3 90
左连接语句
no name no grade
1 a 1 90
2 b 2 80
3 c 3 85
3 c 3 90
4 d NULL NULL
右连接语句
no name no grade
1 a 1 90
2 b 2 80
3 c 3 85
3 c 3 90
全连接语句
no name no grade
1 a 1 90
2 b 2 80
3 c 3 85
3 c 3 90
4 d NULL NULL
总结:
从上面例子可以看出:
内连接和我们平时所用的where语句效果一致,即两个表的共同的部分
外连接包括(左连接、右连接)
左连接,即已左边的表为主表,右边的表为副表,将主表中需要的字段全部列出,然后将副表中的数据按照查询条件与其对应起来,
右连接则相反。
全连接,则是将两个表的需要的字段的数据全排列。