我无法理解如何进行一个查询,该查询将在 View 方面向我显示“三篇最受欢迎的文章”(“状态:200 OK”)。
我当前正在处理 2 个表。
- 日志表
- 文章表
这些表中的列: 表“public.log”
Column | Type | Modifiers
--------+--------------------------+--------------------------------------------------
path | text |
ip | inet |
method | text |
status | text |
time | timestamp with time zone | default now()
id | integer | not null default nextval('log_id_seq'::regclass)
索引:
和
Table "public.articles"
Column | Type | Modifiers
--------+--------------------------+-------------------------------------------------------
author | integer | not null
title | text | not null
slug | text | not null
lead | text |
body | text |
time | timestamp with time zone | default now()
id | integer | not null default nextval('articles_id_seq'::regclass)
索引:
.
到目前为止,我已经根据我的水平和当前对 SQL 的理解编写了这个查询...
SELECT articles.title, log.status
FROM articles join log
WHERE articles.title = log.path
HAVING status = “200 OK”
GROUP BY title, status
显然,这是错误的。我希望能够从数据库中提取三篇最受欢迎的文章,并且我知道将 200 个 OK 与“文章标题”进行“匹配”将为我显示或计入一次“查看”或点击。我的思考过程是这样的,我需要通过创建查询来确定article.title=log.path(1个唯一)在日志数据库中出现的次数(状态为200 OK)。我的任务实际上是编写一个程序,该程序将打印结果,“[我的代码获取]数据库通过使用联接、聚合和 where 子句来完成繁重的工作。在 Python 代码中进行最少的“后处理”本身。”
任何解释、想法、提示都将受到 StackOverflow 的欢迎...
最佳答案
也许您想到的是以下内容:
SELECT
a.title,
COUNT(*) AS cnt
FROM articles a
INNER JOIN log l
ON a.title = l.path
WHERE
l.lstatus = '200 OK'
GROUP BY
a.title
ORDER BY
COUNT(*) DESC
LIMIT 3;
这将返回具有最高状态 200 个点击数的三篇文章标题。此答案假设您正在使用 MySQL。
关于python - SQL join、where、having 子句出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464140/