-- 方法1:每组前2条,再截取
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.ids,',',help_topic_id+1),',',-1) AS num
FROM mysql.help_topic,
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(c.id ORDER BY c.date desc, c.title asc), ",", 2) AS ids FROM content c GROUP BY c.type) as t
WHERE help_topic_id < LENGTH(t.ids)-LENGTH(REPLACE(t.ids,',',''))+1;
-- 方法2:每组前2条,再包含
UPDATE content cont,
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(c.id ORDER BY c.date desc, c.title asc), ",", 2) AS ids FROM content c GROUP BY c.type) t
SET cont.state = 0
WHERE find_in_set(cont.id, t.ids);
说明:建表数据就不提供了,就是表content,字段type分组后,每组date倒序、title顺序,取前2条数据,修改state值。
总结:方法1查询较快,但update不好写很慢。方法2查询较慢,但update很快。
另附:函数循环参考