避免空返回集

时间:2011-11-15 15:10:18

标签: mysql sql

如何查询总是返回一些东西,当它找不到我要找的东西时是默认值?

例如,在以下查询中:

SELECT 
            food_id,
            drink_id,
            payment_amount, 
            count(*) AS total_payments,
            payment_amount * count(*) AS total_benefit
            FROM foods pc
            INNER JOIN drinks px
            ON pc.id = px.food_id
            AND pc.drink_id = 25
            GROUP BY food_id, drink_id;

当pc.id不等于px.food_id时,我得到一个空集。我正在寻找以下内容:

SELECT 
            food_id DEFAULT IF NOTHING 5,
            drink_id DEFAULT IF NOTHING 25,
            payment_amount DEFAULT IF NOTHING 0, 
            count(*) AS total_payments DEFAULT IF NOTHING 0,
            payment_amount * count(*) AS total_benefit DEFAULT 0
            FROM foods pc
            INNER JOIN drinks px
            ON pc.id = px.food_id
            AND pc.drink_id = 25
            GROUP BY food_id, drink_id;

任何做上述事情的方式?

3 个答案:

答案 0 :(得分:3)

由于内部联接,您获得的是空结果集。这可能应该是外连接。将此与Rup的答案结合起来可能正是您所寻找的:

SELECT 
        COALESCE(food_id, 0) AS food_id,
        COALESCE(drink_id, 25) AS drink_id,
        COALESCE(payment_amount, 0) as payment_amount,
        count(*) AS total_payment,
        COALESCE(payment_amount, 0) * count(*) AS total_benefit
        FROM foods pc
        LEFT OUTER JOIN drinks px
        ON pc.id = px.food_id
        AND pc.drink_id = 25
        GROUP BY food_id, drink_id;

答案 1 :(得分:1)

您可能需要COALESCE

SELECT 
            COALESCE(food_id, 0) AS food_id,
            COALESCE(drink_id, 25) AS drink_id,
            COALESCE(payment_amount, 0) as payment_amount,
            count(*) AS total_payment,
            COALESCE(payment_amount, 0) * count(*) AS total_benefit
            ...
GROUP BY COALESCE(food_id, 0), COALESCE(drink_id, 25),
         COALESCE(payment_amount, 0);

答案 2 :(得分:0)

SELECT food_id, drink_id, payment_amount, COUNT(*) AS total_payments,
      payment_amount * COUNT(*) AS total_benefit
   FROM foods pc 
      INNER JOIN drinks px
         ON pc.id = px.food_id
            AND pc.drink_id = 25
   GROUP BY food_id, drink_id 
UNION
SELECT 0, 0, 0, 0, 0
   FROM MySystemTableAlwaysHasExactlyOneRow 
  WHERE NOT EXISTS (
                    SELECT * 
                      FROM foods pc 
                         INNER JOIN drinks px
                            ON pc.id = px.food_id
                               AND pc.drink_id = 25
                     ) ;