2017-06-09 98 views
1

我用一個簡單的存儲過程,努力從2個表收集數據併發送回PHP:mysql如何返回NULL值,如果沒有記錄

BEGIN 

DECLARE cur_name VARCHAR(50); 

SELECT currency_name INTO cur_name FROM currencies WHERE id = currency_id_var; 
SELECT cur_name, sum(amount) AS income_amount, currency_id, month(income_date) AS month_of_income 
    FROM incomes 
    WHERE user_id = user_id_var 
     AND currency_id = currency_id_var 
     AND income_date > year_beginning_var 
     AND month(income_date) = month_var 
    GROUP BY currency_id; 

END 

它的工作好,除非是在'收入'表中找不到記錄。我需要使用'cur_name'設置(它始終有一些值)和其餘變量(income_amount,currency_id,month_of_income)設置爲NULL的過程的響應。 我在問一些無法做到的事情嗎? 我試圖使它與選擇IFNULLUNION SELECT NULL種命令,沒有成功... 謝謝!

+0

我不確定,但你應該檢查[this](https://stackoverflow.com/questions/28089275/select-statement-to-return-constant-when-no-records-found-in-table-in -sql-server#answer-28090639) –

回答

0

你可以兩個查詢合併成一個LEFT JOIN,像這樣:

SELECT currency_name as cur_name, 
     income_amount, 
     currency_id, 
     month_of_income 
    FROM currencies 
    LEFT JOIN 
     (
      SELECT cur_name, sum(amount) AS income_amount, currency_id, month(income_date) AS month_of_income 
       FROM incomes 
       WHERE user_id = user_id_var 
        AND currency_id = currency_id_var 
        AND income_date > year_beginning_var 
        AND month(income_date) = month_var 
       GROUP BY currency_id; 
     ) 
     ON currency_id = currencies.id 
    WHERE currencies.id = currency_id_var; 

未經檢驗的,但你的想法:這是一個LEFT JOIN,所以它是保證返回至少一行對每個匹配行左表(currencies),如果右表(子查詢)不產生任何結果,則相應的字段將返回爲NULL

爲了更好的可讀性,我會考慮將子查詢移動到視圖,然後左鍵連接。

+0

感謝您的回覆!我明白了,但我不是SQL專家,看起來代碼段中存在語法錯誤(SQL錯誤1064)... – dujmovicv

+0

子查詢必須有別名 - 在這種情況下)和我建議)s上 –

相關問題