复合mysql选择After outer join

时间:2013-02-07 08:03:57

标签: mysql sql join left-join outer-join

我有一个带有列(a,b)的表A和一个带有列(b,c)的表B.我想做以下事情:

STEP 1: do a   A LEFT OUTER JOIN B ON A.b = B.b
STEP 2: convert all c = NULL in the Joined table to c = <default_value>
STEP 3: SUM(A.a * B.c) over the table I get after STEP 2

在一个复合语句中有快速的方法吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以在一个查询中执行这三个步骤,首先LEFT OUTER JOIN并使用IFNULLNULL值设置为默认值,然后使用SUM

SELECT
  SUM(A.a + IFNULL(B.c, <default_value>))
FROM A 
LEFT OUTER JOIN B ON A.b = B.b;

SQL小提琴演示:

答案 1 :(得分:0)

select
  sum(A.a + IFNULL(B.c, some_default)) as some_sum
FROM
  A
  LEFT JOIN B
    ON
      B.b = A.b

答案 2 :(得分:0)

 select sum(A.a * (case when B.c = null then <default> else B.c end)) as joined_sum
 from A left outer join B on (A.b = B.b);