简体   繁体   English

如何重写以下mysql查询

[英]How to re-write the following mysql query

I have a file upload site, and I want to run a maintenance script that will run every day and delete items that haven't been accessed in a week. 我有一个文件上传站点,我想运行一个维护脚本,该脚本每天运行,并删除一周内未访问的项目。 I log views for each day, and each item into a table: 我将每天的视图和每个项目记录到一个表中:

  • hit_itemid
  • hit_date
  • hit_views

The main table actually has the files that were uploaded, for the purposes of this example, its just vid_id , vid_title thats in this table, and vid_id will equal to hit_itemid . 在此示例中,主表实际上具有上载的文件,在此表中,它只是vid_idvid_title多数民众赞成,而vid_id等于hit_itemid

I have a query as follows: 我有一个查询如下:

 SELECT vid_id, 
        vid_title, 
        SUM(case when hit_date >= '2009-09-17' then hit_hits else 0 end) as total_hits 
   FROM videos
  LEFT JOIN daily_hits ON vid_id = hit_itemid 
  WHERE vid_posttime <= '$last_week_timestamp' AND vid_status != 3
  GROUP BY hit_itemid 
  HAVING  total_hits < 1

But this always returns a single record. 但这总是返回一条记录。

How can I rewrite this query? 如何重写此查询?

An idea: 一个主意:

SELECT DISTINCT
    vid_id, vid_title
  FROM
    videos v
    LEFT JOIN daily_hits dh ON (
      v.vid_id = dh.hit_itemid AND dh.hit_date >= '2009-09-17'
    )
  WHERE
    v.vid_posttime <= '$last_week_timestamp' AND v.vid_status != 3
    AND dh.hit_itemid IS NULL;

Alternatively (benchmark to see which is faster): 或者(基准测试,看看哪个更快):

SELECT
    vid_id, vid_title
  FROM
    videos v
  WHERE
    v.vid_posttime <= '$last_week_timestamp' AND v.vid_status != 3
    AND NOT EXISTS (
      SELECT 1 FROM daily_hits dh
        WHERE v.vid_id = dh.hit_itemid AND dh.hit_date >= '2009-09-17'
   )

I'm guessing the first form will be faster, but can't check (I don't have access to your data). 我猜第一种形式会更快,但无法检查(我无法访问您的数据)。 Haven't tested these queries either, for the same reason. 出于相同的原因,也没有测试这些查询。

first guess, may be you have to do a 第一次猜测,可能是你必须做一个

GROUP BY vid_id

instead of 代替

GROUP BY hit_itemid
SELECT 
   vd.vid_id, 
   vd.vid_title, 
   sum(case when dh.hit_date >= '2009-09-17' then dh.hit_views else 0 end) as total_hits 
  FROM videos vd
  LEFT JOIN daily_hits dh ON dh.hit_itemid = vd.vid_id
  WHERE vd.vid_posttime <= '$last_week_timestamp' AND vd.vid_status != 3
  GROUP BY vd.vid_id
  HAVING  total_hits < 1

This is how I would have the query... Assuming vid_posttime & vid_status are fields of table videos 这就是查询的方式...假设vid_posttime和vid_status是表格视频的字段

Do you definitely have data which satisfy this criteria? 您肯定有满足此条件的数据吗? You're only considering rows for videos created before a certain timestamp and with a certain status -- perhaps this is limiting your result set to where only one video matches. 您只考虑在特定时间戳之前和具有特定状态创建的视频的行-也许这会将结果集限制为只有一个视频匹配的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM