2017-07-13 74 views
0

我有一個數據庫用於管理項目的多個庫存位置。 我有3個表所示:mysql查詢列出所有具有外鍵的項目到股票的位置

table_items 
+----------+-------------+ 
| id_items |  name | 
+----------+-------------+ 
| 1  | item 1 | 
| 2  | item 2 | 
+----------+-------------+ 

table_location 
+-------------+-------------+ 
| id_location |  name | 
+-------------+-------------+ 
| 1   | location 1| 
| 2   | location 2| 
+-------------+-------------+ 

table_stock 
+-------------+-----------+----------+ 
| id_location | id_item | stock | 
+-------------+-----------+----------+ 
| 1   | 1  |  3 | 
| 1   | 2  |  0 | 
| 2   | 1  |  1 | 
+-------------+-----------+----------+ 

現在我怎麼能列出每個位置,包括不存在有項目的所有項目。例如,我想在位置2項,這樣的結果將是:

+-------------+-----------+----------+ 
| id_location | id_item | stock | 
+-------------+-----------+----------+ 
| 2   | 1  |  1 | 
| 2   | 2  | null | 
+-------------+-----------+----------+ 

也許還有其他的方式做這樣的事情..?

回答

0
SELECT 
    a.* 
FROM 
    (SELECT 
    i.`id_items`, 
    CASE WHEN s.id_location=2 THEN s.id_location ELSE 2 END AS id_location, 
    CASE WHEN s.id_location=2 THEN s.`stock` ELSE 0 END AS stock 
    FROM 
    table_items i 
    LEFT JOIN `table_stock` s 
     ON i.`id_items` = s.`id_items` 
    WHERE id_location = 2 
    UNION 
    SELECT 
    i.`id_items`, 
    CASE WHEN s.id_location=2 THEN s.id_location ELSE 2 END AS id_location, 
    CASE WHEN s.id_location=2 THEN s.`stock` ELSE 0 END AS stock 
    FROM 
    table_items i 
    LEFT JOIN `table_stock` s 
     ON i.`id_items` = s.`id_items` 
    WHERE id_location != 2 
    AND i.id_items NOT IN 
    (SELECT 
     i.`id_items` 
    FROM 
     table_items i 
     LEFT JOIN `table_stock` s 
    ON i.`id_items` = s.`id_items` 
    WHERE id_location = 2)) a 

我通過使用這個查詢得到它現在,任何意見優化..?

0

嘗試此查詢:

SELECT s.id_location, i.id_items, CASE WHEN sum(stock)=0 THEN null ELSE sum(stock) END AS stock 
FROM table_items i LEFT JOIN table_stock s ON i.id_items=s.id_items 
WHERE s.id_location=2 
GROUP BY s.id_location, i.id_items; 

這會給你的位置&項明智的總存量。希望這會解決你的問題。

+0

我認爲這裏有一些缺失,結果不像我想要的那樣喜歡我的問題中的例子。我需要** id_location **和** id_item **,至於它的罰款是否得到0或null – inumaru

+0

@inumaru根據我瞭解您的要求,我認爲這應該工作。此查詢將爲您提供位置和項目明智的總庫存。如果你只需要位置明智,那麼你可以從投影&group by中刪除id_items。對於物品也適用Visa。 –

+0

我的要求是針對一個位置中的所有商品的列表,包括那些沒有像我的示例那樣的位置的商品的商品。我嘗試了你的,但是當我添加'where id_location = 2'時,我無法獲得所有項目。 – inumaru