多个表-基于Where子句的最低值

时间:2019-05-21 00:50:34

标签: sql

当前有3个表,其以下各列,

Table 1
item_id | cost_price

Table 2 
item_id | cost_price

Table 3
item_id | cost_price

需要按子项要按item_id排序的三个表之间的最小值进行排序。 item_id在所有3个表之间共享。

我知道它可能是带有INNER联接的子查询?但我不确定如何编写...

SELECT table1.cost_price, table2.cost_price, table3.cost_price FROM table2
INNER JOIN table1
ON table1.item_id= table2.item_id
INNER JOIN table3
ON table3.item_id= table1.item_id

我希望按查询中的最低cost_Price进行排序。但是我不确定是否应该使用内部联接。

2 个答案:

答案 0 :(得分:0)

您要寻找union all吗?

select item_id, cost_price from table1
union all
select item_id, cost_price from table2
union all
select item_id, cost_price from table3
order by cost_price;

答案 1 :(得分:0)

也许带有CASE语句(未经测试):

SELECT ABC.item_id
,   CASE
        WHEN ABC.t1_min_price < ABC.t2_min_price AND ABC.t2_min_price < ABC.t3_min_price THEN ABC.t1_min_price
        WHEN ABC.t1_min_price > ABC.t2_min_price AND ABC.t2_min_price > ABC.t3_min_price THEN ABC.t3_min_price
        ELSE ABC.t2_min_price
    END AS [min_price]
FROM (
    SELECT t1.item_id
    , (SELECT MIN(X.cost_price) fROM table1 AS X WHERE X.item_id = t1.item_id) AS [t1_min_price]
    , (SELECT MIN(Y.cost_price) fROM table2 AS Y WHERE Y.item_id = t1.item_id) AS [t2_min_price]
    , (SELECT MIN(Z.cost_price) fROM table3 AS Z WHERE Z.item_id = t1.item_id) AS [t3_min_price]
    FROM table1 AS t1
) AS ABC

或者,扩展其他用户的答案:

SELECT X.item_id
, MIN(X.min_price) AS [lowest_price]
FROM (
    SELECT item_id, MIN(cost_price) AS [min_price] FROM table1
    UNION
    SELECT item_id, MIN(cost_price) AS [min_price] FROM table2
    UNION
    SELECT item_id, MIN(cost_price) AS [min_price] FROM table3
) AS X

问题是,当您开始以相同的最低价格购买多于一件商品时,除非没关系。如果是这样,只需...按顺序排序并选择TOP 1或LIMIT 1。