一、分组查询
先连接表,再分组查询
需求:查询每一个出版社出版的名称以及书籍个数
SQL连接表:
SELECT * FROM app_book INNER JOIN app_publish on app_book.publish_id = app_publish.nid
ORM连接表:
Book.objects.values("publish").values()
SQL链表后分组:
SELECT count(title),app_publish.name FROM app_book INNER JOIN app_publish on app_book.publish_id = app_publish.nid GROUP BY publish_id
ORM链表后分组,方式一:
Publish.objects.values("name").annotate(Count("book__title"))
ORM链表后分组,方式二:
通过values拿所需数据即可
Publish.objects.values("nid").annotate(c=Count("book__title")).values(‘name‘,"c")
练习二:
查询每一个作者的名字以及出版过的书籍的最高价格
SQL语法:
SELECT app_author.name,max(price) FROM app_author INNER JOIN app_book_authors ON app_author.nid = app_book_authors.author_id INNER JOIN app_book ON app_book_authors.book_id = app_book.nid ORDER BY app_author.nid
ORM操作:
原文地址:https://www.cnblogs.com/yaya625202/p/9302226.html
时间: 2024-10-11 17:35:38