2015-08-08 83 views
0

我的MySQL結構爲:PHP的MySQL行依賴性檢查

id Ergebnis gewinn multi 
1 gewonnen 2  8550 
2 verloren 0  8550 
3 gewonnen 2  6990 
4 gewonnen 5  6990 
5 gewonnen 12  1443 
6 verloren 0  2201 

我需要從gewinn值算在一起,其中多是一樣的,但只有當ergebnis == gewonnen(所有帶同多值),如果一個或全部ergebnis = verlorenmulti == verloren。因此在本例正確的輸出將是:

8550 == verloren/0 
6990 == gewonnen/7 
1443 == gewonnen/12 
2201 == verloren/0 
+0

8550 gewonnen發生了什麼事? – Strawberry

+0

此外結果表似乎是多餘的。 0總是等於'輸' – Strawberry

+0

http://sqlfiddle.com/#!9/9a31e/3 – Strawberry

回答

0

考慮以下...爲同一

CREATE TABLE my_table 
(id INT NOT NULL AUTO_increment primary key 
, result varchar(12) 
, winnings int 
, multi int 
); 

insert into my_table values 
(1 ,'win', 2 , 8550), 
(2 ,'lose', 0 , 8550), 
(3 ,'win', 2 , 6990), 
(4 ,'win', 5  , 6990), 
(5 ,'win', 12 , 1443), 
(6 , 'lose', 0 , 2201); 

select x.result 
    , sum(z.winnings) total 
    , x.multi 
    from my_table x 
    join 
    (SELECT MULTI 
      , MAX(ID) max_id 
     FROM MY_table 
     group 
      by multi 
    ) y 
    on y.multi = x.multi 
    and y.max_id = x.id 
    join my_table z 
    on z.multi = x.multi 
    and z.result = x.result 
group 
    by x.multi, x.result; 
+--------+-------+-------+ 
| result | total | multi | 
+--------+-------+-------+ 
| win | 12 | 1443 | 
| lose |  0 | 2201 | 
| win |  7 | 6990 | 
| lose |  0 | 8550 | 
+--------+-------+-------+ 

小提琴:http://sqlfiddle.com/#!9/9a31e/3

編輯:粗擴展這個想法 - 返回丟失/ 0,如果多發生任何損失...

SELECT COALESCE(b.result,a.result) result 
    , COALESCE(b.winnings,a.total) total 
    , a.multi 
    FROM 
    ( 
    select x.result 
    , sum(z.winnings) total 
    , x.multi 
    from my_table x 
    join 
    (SELECT MULTI 
      , MAX(ID) max_id 
     FROM MY_table 
     group 
      by multi 
    ) y 
    on y.multi = x.multi 
    and y.max_id = x.id 
    join my_table z 
    on z.multi = x.multi 
    and z.result = x.result 
group 
    by x.multi, x.result 
    ) a 
    LEFT JOIN my_table b 
    ON b.multi = a.multi 
    AND b.result = 'lose'; 
+0

沒有錯誤,但是當你改變行時結果並不如預期。必須有一個檢查,如果多==失去完成多=失去,然後採取。只有當所有的id都是win時,纔會計算結果 – Sascha

+0

請參閱上面的編輯。 – Strawberry

+0

好的thx,按預期工作。感謝幫助 – Sascha

0

如果你改變插入:

insert into my_table values 
(1 ,'lose', 0 , 8550), 
(2 ,'win', 2 , 8550), 
(3 ,'win', 2 , 6990), 
(4 ,'win', 5  , 6990), 
(5 ,'win', 12 , 1443), 
(6 , 'lose', 0 , 2201); 

結果對於例如爲:8550 - >贏得 但應該賠。 在任何id相同的情況下多==輸完整多應該是結果丟失