[英]How to insert same data in 1 table and Limit it by 10
I am working in a "Recently view by user" script. 我正在使用“最近用户查看”脚本。 I have 3 tables, tbl_user, tbl_articles and tbl_recently_viewed.
我有3个表, tbl_user, tbl_articles and tbl_recently_viewed.
My tbl_recently_viewed has 3 fields, user_id(from tbl_user),article_id(from tbl_articles) and date,
and i made 2 primary keys, user_id and article_id.
我的tbl_recently_viewed有3个字段, user_id(from tbl_user),article_id(from tbl_articles) and date,
我制作了2个主键, user_id and article_id.
My problem is i want to limit a certain user_id to be inserted in tbl_recently_viewed by 10. Is there a way i can do this? 我的问题是我想限制某个user_id插入到tbl_recently_viewed中10.有没有办法可以做到这一点?
Thanks. 谢谢。
I think that you need a trigger to do what you want to do. 我认为你需要一个触发器去做你想做的事情。 If you are only inserting rows, then you can use an insert trigger to remove the oldest. 如果只插入行,则可以使用插入触发器删除最旧的行。
The following is intended just as an example: 以下仅作为示例:
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;
|
To delete the oldest item for a user from tbl_recently_viewed
: 要从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 = ?
You could delete rows after 10 with this query: 您可以使用此查询删除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);
or just delete oldest row with query: 或者只是用查询删除最旧的行:
delete from tbl_recently_viewed where user_id=1 order by date limit 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.