0
"id"    "type"  "parent"    "country"   "votes" "perCent"
"1"     "1"     "0"         "US"        "0"     "0"
"2"     "2"     "1"         "US"        "0"     "0"//votes = 8 i.e total of id3 votes and id7votes. Both have id=2 as parent, and id=2 is type 2
"3"     "3"     "2"         "US"        "4"     "0"
"7"     "3"     "2"         "US"        "4"     "0"
"19"    "3"     "1"         "US"        "4"     "0"
"4183"  "10"    "3"         "US"        "2"     "0"
"4184"  "10"    "3"         "US"        "2"     "0"
"4185"  "10"    "7"         "US"        "2"     "0"
"4186"  "10"    "7"         "US"        "2"     "0"
"4187"  "10"    "19"        "US"        "2"     "0"
"4188"  "10"    "19"        "US"        "2"     "0"

我正在尝试type=2用其 id 为父级的投票总和来更新 col。我一直在尝试以下方法,但似乎无处可去,因为这涉及 3 条语句,而且我在连接和多项选择方面非常落后。

UPDATE  likesd a
        INNER JOIN
        (
            SELECT  parent, SUM(votes) totalVotes
            FROM    likesd
            WHERE   type = 3
            GROUP   BY parent
        ) b ON a.country = b.country
SET     a.votes = b.totalVotes
WHERE   a.id = b.parent;

它实际上是这样的:

select id from likesd where type = 2
select sum(votes) as totalVotes where parent = id
update likesd set votes = totalVotes where id = parent and country = country

知道如何做到这一点。我可以选择两次,但第三次被卡住了。

编辑: 类型 = 表中的 2 次重复

4

3 回答 3

1
UPDATE likesd a, (SELECT Parent, SUM(Votes) as TotalVotes
                  FROM likesd
                  GROUP BY Parent) b
SET a.Votes = b.TotalVotes
WHERE a.Type = 2
    AND a.id = b.parent

参考:您不能在 FROM 子句中指定要更新的目标表

于 2013-05-20T05:16:21.913 回答
1

试试这样...

  UPDATE  likesd  inner join 
(Select id, ifnull((Select Sum(Votes) from Likesd A where A.parent=B.Id),0) as suvotes from Likesd) B on B.id=likesd.Id
    Set likesd.Votes=B.suvotes
    where type=2
于 2013-05-20T04:46:18.263 回答
0

当从同一个表中选择和更新时,您不能在 from 中指定 taget 表。这不能在没有程序的情况下完成。如果你愿意,有一种方法可以做到这一点。

CREATE TABLE temp SELECT * FROM likesd;
UPDATE  likesd  B
SET B.votes=(SELECT SUM(votes) FROM temp A WHERE  A.parent=B.TYPE)
WHERE TYPE=2; 
DROP TABLE temp;

在您的代码中一一运行所有查询。

于 2013-05-20T04:55:42.513 回答