SQL表视图JOIN返回最小值

Posted

技术标签:

【中文标题】SQL表视图JOIN返回最小值【英文标题】:SQL table view JOIN returning minimum value 【发布时间】:2019-03-12 05:04:05 【问题描述】:

我有两张桌子

      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

【问题讨论】:

【参考方案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;

【讨论】:

【参考方案2】:

如果你总是有两个部分,我会使用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;

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

如果某些部分可能丢失,那么您需要 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;

【讨论】:

【参考方案3】:

使用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

【讨论】:

【参考方案4】:

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

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

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

【讨论】:

以上是关于SQL表视图JOIN返回最小值的主要内容,如果未能解决你的问题,请参考以下文章

Linq to SQL - 视图与存储过程

ORACLE的SQL JOIN方式小结

SQL Join on Nearest 小于日期

SQL 视图(Views)

SQL JOIN的常见连接算法(转载)

SQL JOIN