用两个选择更新

时间:2013-05-20 04:40:12

标签: mysql sql

"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"

我正在尝试使用其id为父级的投票总数更新col type=2。 我一直在尝试下面的内容,但似乎没有任何地方,因为这涉及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重复

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

参考:You can't specify target table for update in FROM clause

答案 2 :(得分:0)

yoU无法从同一个表中选择和更新时指定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;

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

相关问题