如何在1个表中插入相同的数据并将其限制为10

时间:2013-04-23 01:36:04

标签: mysql

我正在使用“最近按用户查看”脚本。我有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我有办法做到这一点吗?

感谢。

3 个答案:

答案 0 :(得分: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;
|

答案 1 :(得分: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 = ?

答案 2 :(得分: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;