将SQL子查询的结果写回数据库

时间:2013-10-24 00:54:00

标签: mysql sql

我一直在玩这个SQL代码:

SELECT
    id,
    @prev := @curr as prev,
    @curr := measure as curr,
    @rank := IF(@prev > @curr, @rank+@ties, @rank) AS rank,
    @ties := IF(@prev = @curr, @ties+1, 1) AS ties,
    (1-@rank/@total) as percentrank
FROM
    mytable,
    (SELECT
        @curr := null,
        @prev := null,
        @rank := 0,
        @ties := 1,
        @total := count(*) from mytable where measure is not null
    ) b
WHERE
    measure is not null
ORDER BY
    measure DESC

我想将计算出的'percentrank'写回名为“百分位数”的列中mytable的每一对应行,但我不记得如何在我的更新语句中工作。

我很感激帮助。

感谢http://code.openark.org/blog/mysql/sql-ranking-without-self-join获取SQL。

1 个答案:

答案 0 :(得分:1)

要从子查询更新,请为子查询指定别名,以使其成为派生表。然后使用以下语法:

update YourTable
set SomeField = DerivedTable.something
, etc
from YourTable join
(subquery goes here) DerivedTable on YourTable.Whatever  = DerivedTable.Whatever
etc