Mysql - 计算2个不同表中两列之间的差异并插入

时间:2011-08-22 00:49:07

标签: mysql

我有以下语句,需要再添加1个子查询来计算tweeps表中的关注者数量与ranking表中当前列中的数量之间的差异,并插入latest表中名为ranking的列中的差异确定PK是屏幕名称,

在tweeps表中跟随者coulm中的数字是10个当前coulmn n排名表,对于同一个screenname是5,该值将被添加到最新的是+5

mysql_query ("
    INSERT  INTO ranking
    SELECT @rank := @rank + 1, tweeps.* FROM tweeps
    JOIN( SELECT @rank := 0 ) AS init
    ORDER BY followers DESC
    ON DUPLICATE KEY UPDATE
    ranking.ranking = @rank, 
    ranking.name = tweeps.name,
    ranking.followers = tweeps.followers,
    ranking.tweets = tweeps.tweets,
    ranking.location = tweeps.location,
    ranking.`join date` = tweeps.join_date,
    ranking.avatar = tweeps.avatar;");
mysql_close($con);

1 个答案:

答案 0 :(得分:1)

试试这个:

INSERT INTO ranking
SELECT @rank := @rank + 1, tweeps.* FROM tweeps
JOIN( SELECT @rank := 0 ) AS init
ORDER BY followers DESC
ON DUPLICATE KEY 
UPDATE ranking set
ranking = @rank, 
name = tweeps.name,
followers = tweeps.followers - followers,
tweets = tweeps.tweets,
location = tweeps.location,
`join date` = tweeps.join_date,
avatar = tweeps.avatar;

我将语法更改为ON DUPLICATE KEY UPDATE ranking set...