2016-04-07 12 views
1

関連する値の合計を収集:のMySQL:<code>database</code>に私は3つのテーブルを持っている

表:記事

id | code | name   | quantity | stock_date 
-------------------------------------------------- 
1 1dfod Article name 10  2016-04-01 

表:

id | client_id | selling_type_id | selling_date | selling_status 
---------------------------------------------------------------- 
1 1   1     2016-04-02  1 
2 1   1     2016-04-03  1 
3 1   1     2016-04-04  1 

表を販売します: selling_detail

id | selling_id | article_id | quantity 
------------------------------------- 
1 1   1   2 
2 1   1   3 
3 1   1   1 
4 2   1   3 
5 3   1   1 
は、最後に私はこのようなこの記事の stock recordを持っているでしょう:私の知識へ

date  | in_stock (item in stock) | out_stock (sum of item sold) 
---------------------------------------------------------------------- 
2016-04-01 10       0 
2016-04-02 0       6 
2016-04-03 0       3 
2016-04-04 0       1 

すべてmysqlクエリは私にこの結果を与えることはありません。

SELECT SUM(sd.quantity) out_stock, s.search_date, ifnull(ss.quantity, 0) in_stock 
FROM selling_detail sd JOIN selling s ON (sd.selling_id = s.id) 
LEFT JOIN shop_stock ss ON (ss.search_date = s.search_date) WHERE (sd.shop_stock_id = 1) 
GROUP BY s.search_date; 
+3

まあ、少なくとも私達にあなたの最善の努力 – Strawberry

+0

を示しOPが無にしたので、私は、オフトピックとして、この質問を閉じるために投票しています彼自身の問題を解決する努力 ' –

答えて

1
SELECT date,SUM(in_stock) in_stock,SUM(out_stock) out_stock FROM 
(
SELECT stock_date date,quantity in_stock,0 out_stock FROM article 
    UNION 
SELECT selling_date,0,quantity FROM selling JOIN selling_detail ON selling_detail.selling_id = selling.id 
) x 
GROUP BY date; 
+0

ありがとう、それは完全に正常に動作します! – nekiala

+0

私はUNION ALLをここに使用したいと思います。あなたはそこに二重引用符がなく、操作を保存しています。私はまた、SUMをサブクエリの中に入れて、一時的なメモリの使用量を少なくすることを望んでいます。 – Arth

0

あなたは2つの非常に異なるテーブルからの同様のデータを結合しようとしているとして、あなたはおそらく、UNION ALLのバレルを見つめされます:

は、ここに私のコードです。

これらの線に沿って何かあなたが始める必要があります。

 SELECT * 
     FROM (
     SELECT a.stock_date `date`, 
       SUM(a.quantity) `in_stock (item in stock)`, 
       0 `out_stock (sum of item sold)` 
      FROM article a 
      WHERE a.id = :article_id 
     GROUP BY `date`   
     UNION ALL 
     SELECT s.selling_date, 
       0,  
       SUM(sd.quantity) 
      FROM selling s 
      JOIN selling_detail sd 
      ON sd.selling_id = s.id 
      AND sd.article_id = :article_id 
     /* WHERE s.selling_type = ?? 
      AND s.selling_status = ?? /* If necessary */ 
     GROUP BY `date`   
      ) sr 
    ORDER BY `date` 
+0

こんにちは、ありがとうございました。しかし、私はいくつかのエラーがあります。 – nekiala

+0

私はあなたが解決策を見つけたのを見ていますが、将来はエラーの内容を詳しく教えてください。 – Arth

関連する問題