2013-04-04 23 views
0

我在想,如果SQL可以自己完成这一点,或者如果我应该使用PHP。 (高尔夫)数据库有rounds表和holes表。 rounds.id存储在该轮的洞记录中。基于连接值的条件更新记录

holes表已(在许多其他领域)firstPuttsecondPutt,thirdPutt。这些浮标存储距离和默认为零。

我的雇主想要做的就是在轮次表中存储该轮中最后一个推杆的最后一推的长度的总和。

我意识到如果我有一个putts表引用holes.id这将是一个更好的结构,但目前是不可能的。

所以在pseudoSQL更新会像

UPDATE holes h, rounds r 
SET r.sumOfLastPutts = (
SELECT thirdPutt if thirdPutt is not 0 
    OR secondPutt if secondPutt is not zero AND thirdPutt is zero 
    OR firstPutt if firstPutt is not zero AND secondPutt is zero) 
) WHERE h.round = rounds.id 

这有可能仅使用SQL?

在这个例子中,这个回合的数字是145,红色框中的数字总和。

data

都会响起马丁帕金的答案,我可以得到一个单轮的总和是这样的:

SELECT 
SUM(
    CASE 
    WHEN h.thirdPutt != 0 THEN h.thirdPutt 
    WHEN h.secondPutt != 0 THEN h.secondPutt 
    WHEN h.firstPutt != 0 THEN h.firstPutt 
    END 
) 
FROM holes h 
WHERE h.round = 3044 

回答

2

你可以尝试以下方法,这似乎提供你在找什么:

UPDATE rounds r, holes h 
    SET r.sumOfLastPutts = 
    CASE 
     WHEN h.thirdPutt != 0 THEN h.thirdPutt 
     WHEN h.secondPutt != 0 THEN h.secondPutt 
     WHEN h.firstPutt != 0 THEN h.firstPutt 
    END 
    WHERE h.round = r.id; 

有一个SQLFiddle演示here

+0

谢谢你的回复!我很高兴在SQL中学习CASE。我不知道。你的答案是接近的,但它不会将多行'holes'记录加在一起,其中h.round = r.id.我在我的问题中添加了一些数据的图片示例。在这个例子中,你的查询得到的值是12,但是总和是145. – jerrygarciuh 2013-04-04 20:19:46

+0

把它排序。谢谢教我关于CASE! – jerrygarciuh 2013-04-04 21:21:48

0

这做工作:

UPDATE rounds r 
    SET r.totalPuttDistance = (
    SELECT 
     SUM(
     CASE 
      WHEN h.thirdPutt != 0 THEN h.thirdPutt 
      WHEN h.secondPutt != 0 THEN h.secondPutt 
      WHEN h.firstPutt != 0 THEN h.firstPutt 
     END 
     ) 
    FROM holes h 
    WHERE h.round = r.id 
)