-1
"id"    "type"  "parent"    "country"   "votes" "perCent"
"1"     "1"     "0"         "US"        "0"     "0"
"2"     "3"     "1"         "US"        "105"   "0"// Total
"3"     "10"    "2"         "US"        "15"    "0"
"4"     "10"    "2"         "US"        "50"    "0"
"5"     "10"    "2"         "US"        "25"    "0"
"6"     "10"    "2"         "US"        "5"     "0"
"7"     "10"    "2"         "US"        "10"    "0"

"8"     "1"     "0"         "US"        "0"     "0"
"9"     "3"     "8"         "US"        "80"    "0"// Total
"10"    "10"    "9"         "US"        "10"    "0"
"11"    "10"    "9"         "US"        "5"     "0"
"12"    "10"    "9"         "US"        "15"    "0"
"13"    "10"    "9"         "US"        "20"    "0"
"14"    "10"    "9"         "US"        "30"    "0"

在上表中likes,我将总票数存储在 type = 3 行中。

我正在尝试perCent使用 type = 10 的每个获得的投票百分比来更新该列。

我现在在 php 中执行此操作,如下所示。前两个语句可以合并为一个吗?我失去了尝试连接和内部连接等。

我目前在php中做事的方式如下:

select id, votes as totalVotes from likes where type = 3 and country = 'us';

select votes from likes where parent = id and type = 10;

update votes set votes = (100*10/totalVotes) where type = 10 and parent = id;

我试图达到的结果:

"id"    "type"  "parent"    "country"   "votes" "perCent"
    "1"     "1"     "0"         "US"        "0"     "0"
    "2"     "3"     "1"         "US"        "105"   "0"// Total
    "3"     "10"    "2"         "US"        "15"    "14.28" (100*15/105)
    "4"     "10"    "2"         "US"        "50"    "47.61"
    "5"     "10"    "2"         "US"        "25"    "23.80"
    "6"     "10"    "2"         "US"        "5"     "4.76"
    "7"     "10"    "2"         "US"        "10"    "9.53"

    "8"     "1"     "0"         "US"        "0"     "0"
    "9"     "3"     "8"         "US"        "80"    "0"// Total
    "10"    "10"    "9"         "US"        "10"    "12.5"
    "11"    "10"    "9"         "US"        "5"     "6.25"
    "12"    "10"    "9"         "US"        "15"    "18.75"
    "13"    "10"    "9"         "US"        "20"    "25.00"
    "14"    "10"    "9"         "US"        "30"    "37.50"
4

3 回答 3

1

Check SQLFiddle .

UPDATE `votestable` v
SET v.`percent` = (SELECT
                     ROUND( ( ( v.votes * 100) / v1.votes ), 2 )
                   FROM (SELECT
                           votes,
                           id
                         FROM Votestable) AS v1
                   WHERE v1.id = v.parent)
于 2013-05-18T07:18:28.823 回答
1

这应该符合您的要求,更新所有产品的百分比以反映它们在其标题下的总票数中的部分;

UPDATE likes p
JOIN likes h
  ON p.parent = h.id
 AND p.type=10 AND h.type=3
 AND h.country = 'US'
SET p.percent=100*p.votes/h.votes;

一个用于测试的 SQLfiddle

于 2013-05-18T07:36:51.750 回答
0

如果我没记错的话,这对我来说就像是左连接。

SELECT lp.id, lp.votes + COALESCE(SUM(lc.votes), 0) as totalVotes FROM likes lp
    LEFT JOIN likes lc ON lc.parent = lp.id AND lc.type = 10
    WHERE lp.type = 3 AND lp.country = 'us'
于 2013-05-18T06:56:20.597 回答