mysql组合表连接

时间:2017-08-03 02:01:58

标签: mysql join subquery

感谢您的评论我将从另一个角度尝试这一点。

如何编写此查询以产生这些结果?

    CompID  CompeteID   Casting     Fishing     Total    
         1      1       265.89    425.56       691.45   
         1      9       212.31     84.76       285.92   
         1      7         0.00    285.92       285.92   
         1      8         0.00     44.52        44.52   
   ORDER BY Total DESC

SELECT cs.CompID, ic.CompeteID 
 , MAX(IF(cast.CastType_ID BETWEEN 6 AND 12, cast.Length, 0)) + SUM(IF(cast.CastType_ID < 6, 40 - (cast.Length * 2), 0)) AS 'Casting' 
FROM `comp-setup` cs
INNER JOIN `input-competitor` ic 
    ON cs.CompID = ic.Comp_ID 
LEFT JOIN `input-casting` cast 
    ON cast.Compete_ID = ic.CompeteID 
GROUP BY ic.CompeteID

UNION ALL 

SELECT cs.CompID, ic.CompeteID
, SUM((iw.Weight * ca.Factor) + '1') AS 'Fishing'
FROM `comp-setup` cs
INNER JOIN `input-competitor` ic 
    ON cs.CompID = ic.Comp_ID 
LEFT JOIN `input-weighin` iw 
    ON iw.Compete_ID = ic.CompeteID
INNER JOIN `input-catchpoints` ca 
    ON ca.PointsCatchID = iw.PointsCatch_ID
GROUP BY ic.CompeteID

以上查询的结果,我添加了break-line和Fishing标题来分隔数据。

    CompID  CompeteID   Casting 
        1       1        265.89 
        1       7             0 
        1       8             0 
        1       9        212.31 
----------------------------------
                        Fishing
        1       1        425.56 
        1       7        285.92 
        1       8         44.52 
        1       9         84.76 

1 个答案:

答案 0 :(得分:0)

这让我花了很多时间。我今天发现这个例子引导我找到这个解决方案,如果有更好的方法,请发帖吗?但这就是我需要的!

    SELECT Sub1.CompID, Sub1.CompeteID, Sub2.Casting, Sub1.Fishing, Sub2.Casting + Sub1.Fishing AS Total
FROM 
    (SELECT cs.CompID, ic.CompeteID, SUM((iw.Weight * ca.Factor) + '1') AS Fishing
FROM `comp-setup` cs
    INNER JOIN `input-competitor` ic ON cs.CompID = ic.Comp_ID 
    INNER JOIN `input-weighin` iw ON iw.Compete_ID = ic.CompeteID
    INNER JOIN `input-catchpoints` ca ON ca.PointsCatchID = iw.PointsCatch_ID
    INNER JOIN `list-grade` gr ON ic.Grade_ID = gr.GradeID 
    INNER JOIN `list-division` ld ON ic.Div_ID = ld.DivID 
    GROUP BY ic.CompeteID) Sub1

INNER JOIN 

(SELECT cs.CompID, ic.CompeteID, MAX(IF(cast.CastType_ID BETWEEN 6 AND 12, cast.Length, 0)) + SUM(IF(cast.CastType_ID < 6, 40 - (cast.Length * 2), 0)) AS Casting 
FROM `comp-setup` cs 
    INNER JOIN `input-competitor` ic ON cs.CompID = ic.Comp_ID 
    LEFT JOIN `input-casting` cast ON cast.Compete_ID = ic.CompeteID 
    GROUP BY ic.CompeteID) Sub2

ON Sub1.CompeteID = Sub2.CompeteID
ORDER BY Total DESC

以下是我需要的示例帖子: MYSQL LEFT JOIN with GROUP BY

相关问题