将两个选择的SQL查询合并为一个

时间:2013-05-18 06:47:58

标签: mysql sql

"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行中。

我正在尝试使用每个类型= 10的投票百分比更新perCent列。

我现在在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"

3 个答案:

答案 0 :(得分:1)

检查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)

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

An SQLfiddle to test with

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