文章模型如下
class Article(models.Model):
title = models.CharField(max_length=150, verbose_name='文章标题', unique=True) content = models.TextField(verbose_name='文章内容') describe = models.CharField(max_length=500, verbose_name='文章描述', blank=True, null=True) date_publish = models.DateTimeField(auto_now_add=True, verbose_name="发布时间") click_count = models.PositiveIntegerField(verbose_name='点击次数', blank=True, null=True, default=0) keywords = models.ForeignKey(Keywords, blank=True, null=True, verbose_name='关键词') class Meta: verbose_name = '文章' verbose_name_plural = verbose_name ordering = ['-date_publish'] def __str__(self): return self.title
查询:若外键字段“keywords”下有多条数据,只取1条,多条数据按click_count取点击数最大的,再得到标题/内容/描述的值,输出到网页模板上。
想用一个查询语法完成,请问如何写呢
代言2017-06-20 10:07:37
关键字mysql分析函数(开窗函数),由于mysql不支持max over只能写成如下:
SELECT tt.*
FROM table tt
INNER JOIN (SELECT
keyword,
max(click_count) maxcount
FROM table
GROUP BY keyword) groupedtt ON tt.keyword = groupedtt.keyword AND tt.click_count = groupedtt.maxcount
ORDER BY tt.create_time