#按用戶名摸糊查詢
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%'python
#左外聯接(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%'session
#以上是已經設置好外鍵,它自動找到關聯的字段.也能夠本身指定:
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%'spa
#另一個更復雜的例子:
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 = %scode
with session() as s: machineList = s.query(OnlinePerfMachine, MachineUsed, OnlinePerfProject).\ outerjoin(MachineUsed, OnlinePerfMachine.machine_id==MachineUsed.machine_id).\ outerjoin(OnlinePerfProject, OnlinePerfProject.project_id==MachineUsed.perf_project_id).all()
等價於:blog
SELECT xxx FROM online_perf_machine LEFT OUTER JOIN machine_used ON online_perf_machine.machine_id = machine_used.machine_id LEFT OUTER JOIN online_perf_project ON online_perf_project.project_id = machine_used.perf_project_idit
上面語句的調試信息:io
在查詢結果裏顯示query()括號裏的內容,所以,你能夠在查詢結果裏獲得匹配的某個表某些字段的信息、幾個表的信息、幾個表的某些字段的信息,好比class
一、匹配到的Table1的全部字段信息sed
二、匹配到的Table一、Table2的全部字段的信息
三、匹配到的Table1.column一、Table1.column二、Table2.column一、Table2.column4這些字段的信息
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語句效果一致,即兩個表的共同的部分
外鏈接包括(左鏈接、右鏈接)
左鏈接,即已左邊的表爲主表,右邊的表爲副表,將主表中須要的字段所有列出,而後將副表中的數據按照查詢條件與其對應起來,
右鏈接則相反。
全鏈接,則是將兩個表的須要的字段的數據全排列。---我這邊實際上報錯
參考:http://www.codexiu.cn/python/blog/727/