mysql查询列出所有具有外键到库存位置的项目

时间:2017-07-13 09:42:27

标签: mysql

我有一个用于管理项目的多个位置库存的数据库。 我有3个像这样的表:

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   |
+-------------+-----------+----------+

或者还有其他办法可以做这样的事情......?

2 个答案:

答案 0 :(得分: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;

这会给你位置&项目明智的总库存。希望这能解决你的问题。

答案 1 :(得分: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

我现在使用此查询得到它,任何意见优化.. ??