开发者

Update one table from another table while using count?

开发者 https://www.devze.com 2023-02-07 13:41 出处:网络
I have stats table with fields id(int开发者_如何转开发) and timestamp(timestamp). SELECT id FROM statsGROUP BY id ORDER BY count(id) DESC LIMIT 10;

I have stats table with fields id(int开发者_如何转开发) and timestamp(timestamp).

SELECT id FROM stats  GROUP BY id ORDER BY count(id) DESC LIMIT 10; 

Gives me the top 10 id's.

I want to put these id's into another table 'popular'

Popular has fields id(int), position(int) and timestamp(timestamp).

To summarize I want to create a query that will update the popular table with the "top 10" id's found in the stats table.


INSERT INTO `popular` (`id`,`position`,`timestamp`)
(
   SELECT `id`,COUNT(`id`),NOW() 
   FROM `stats` GROUP BY `id` 
   ORDER BY COUNT(`id`) DESC LIMIT 10
)

It's not quite an update, though. This'll put the new "top 10" entries from stats into popular, yet retain the "old top 10". A TRUNCATE on popular might be necessary before.

UPDATE: TRUNCATE TABLE will empty a given table. It's almost identical to DELETE FROM but it also resets any primary keys that are auto_increment.

0

精彩评论

暂无评论...
验证码 换一张
取 消