SQL表视图JOIN返回最小值

时间:2019-03-12 05:04:06

标签: mysql sql database-design

我有两个桌子

      Combination
id | front_part | back_part
1  |     2      |     3
2  |     2      |     4

        Parts
id |     name       | inventory
2  |   black front  |     20
3  |   silver back  |     4
4  |   gold back    |     10

此处的组合表具有与零件表相关的两列。我想创建一个视图,该视图返回每个组合的最小库存,这是两个零件的最小库存。

所需表

combination_id |   inventory
            1  |   4
            2  |   10

我得到的

combination_id |   inventory
            1  |   20
            1  |   4
            2  |   20
            2  |   10

我使用的查询:

CREATE view combination_inventory_view as
SELECT combination.id as combination_id,
    parts.inventory as inventory
FROM combination
LEFT JOIN parts 
    ON parts.id = combination.front_part 
    OR parts.id = combination.back_part

4 个答案:

答案 0 :(得分:1)

尝试一下

SELECT combination_id,
 CASE WHEN p1.inventory<=p2.inventory
  THEN p1.inventory
  ELSE COALESCE(p2.inventory,p1.inventory) END AS inventory
FROM combination, parts p1, parts p2
WHERE combination.front_part = p1.id
AND combination.back_part = p2.id;

答案 1 :(得分:0)

使用min()聚合函数和group by

CREATE view combination_inventory_view as
SELECT combination.id as combination_id,
    min(parts.inventory) as inventory
FROM combination
LEFT JOIN parts 
    ON parts.id = combination.front_part 
    OR parts.id = combination.back_part
group by combination.id

答案 2 :(得分:0)

要获取数字列的最大值,请使用MAX()函数。

SELECT MAX(<numeric column>) FROM <table>; SELECT MAX(<numeric column>) FROM <table> GROUP BY <other column>;

要获取数字列的最小值,请使用MIN()函数。

答案 3 :(得分:0)

如果您总是有两个部分,我会使用least()

CREATE view combination_inventory_view as
    SELECT c.id as combination_id,
           LEAST(pf.inventory, pb.inventory) as inventory
    FROM combination c JOIN
         parts pf
         ON pf.id = c.front_part JOIN
         parts pb
         ON pb.id = c.back_part;

这应该比在OR子句中使用ON的查询具有更好的性能。

如果某些部分可能丢失,那么您需要一个LEFT JOIN并需要在LEAST()中进行处理(因此它不会返回NULL):

CREATE view combination_inventory_view as
    SELECT c.id as combination_id,
           COALESCE(LEAST(pf.inventory, pb.inventory), pf.inventory, pb.inventory) as inventory
    FROM combination c LEFT JOIN
         parts pf
         ON pf.id = c.front_part LEFT JOIN
         parts pb
         ON pb.id = c.back_part;
相关问题