0

我正在使用“用户最近查看”脚本。我有 3 个表,tbl_user, tbl_articles and tbl_recently_viewed.我的 tbl_recently_viewed 有 3 个字段,user_id(from tbl_user),article_id(from tbl_articles) and date,我做了 2 个主键,user_id and article_id.我的问题是我想限制某个 user_id 插入 tbl_recently_viewed 到 10。有什么办法可以做到这一点?

谢谢。

4

3 回答 3

1

我认为你需要一个触发器来做你想做的事。如果您只插入行,那么您可以使用插入触发器来删除最旧的。

以下仅作为示例:

CREATE TRIGGER t_keep10 after INSERT ON t
  FOR EACH ROW BEGIN
     if (10 > (select count(*) from t where t.user_id = new.user_id)) then
         delete from t where t.article_id = (select a from (select article_id as a from t t2 where t2.user_id = t.user_id order by date desc limit 1))
     end if;
  END;
|
于 2013-04-23T01:59:40.913 回答
1

要从以下位置删除用户最旧的项目tbl_recently_viewed

DELETE v.* FROM tbl_recently_viewed v
JOIN (SELECT MIN(date) mindate
      FROM tbl_recently_viewed
      WHERE user_id = ?) r
ON v.date = r.mindate
WHERE user_id = ?
于 2013-04-23T02:00:01.103 回答
0

您可以使用此查询删除 10 之后的行:

delete from tbl_recently_viewed where user_id=1 and date <= (select max(date) from (select date from tbl_recently_viewed where user_id=1 order by date desc limit 10,999) as tmp);

或者只是使用查询删除最旧的行:

delete from tbl_recently_viewed where user_id=1 order by date limit 1;
于 2013-04-23T02:12:28.097 回答