python - SQL join、where、having 子句出现问题

标签 python mysql sql database logging

我无法理解如何进行一个查询,该查询将在 View 方面向我显示“三篇最受欢迎的文章”(“状态:200 OK”)。

我当前正在处理 2 个表。

  1. 日志表
  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/

相关文章:

mysql - InnoDB 在导入时转换为 MyISAM

sql - 转置数据布局

python - 如何将 OHLCV 数据重新采样为 5 分钟?

mysql php 查询 : why does a including not equal affect the results

python - 使用 databricks 集群执行 azure 存储上存在的 python 代码

php - Symfony/PHP - 存储单个值的最佳方式

mysql - 如何将本地文本文件中的数据导入到mysql数据库

mysql - 如何正确格式化我的 UPDATE 语句?获取不唯一的表/别名错误

python - 程序,从 10 个中选择最好的

python - 计算 nd 数组中相同子数组的最快方法?