从同一个表中选择多个MIN列和其他数据

时间:2017-04-29 21:00:50

标签: mysql

夜。希望有人能提供帮助。被困了几天了......

我有下表......

| ID | Supplier | Item_1 | Cost_1 | Item_2 | Cost_2 | Item_3 | Cost_3 |
+----+----------+--------+--------+--------+--------+--------+--------+
|  1 |        1 |   732w |   3.99 |   314d |   7.58 |   399p |  15.44 |
|  1 |        2 | SyYh33 |   3.78 | GjuUh4 |   7.60 | 2su7js |  15.45 |
|  1 |        3 |   5443 |   4.01 |   9833 |   7.63 |   7433 |  15.22 |
|  2 |        1 |   596q |  15.42 |   933k |  28.56 |   732c |  69.99 |
|  2 |        2 | hyjs9k |  15.86 | ka7snf |  28.99 | h23nfs |  68.99 |
|  2 |        3 |   5477 |  14.99 |   5658 |  28.49 |   8153 |  70.15 |
+----+----------+--------+--------+--------+--------+--------+--------+

现在我要做的是从Cost_1,Cost_2,Cost_3列返回最便宜的价格,并附上相应的Item列和每个ID的供应商....

所以基本上想要以下结果

| ID | Supplier_1 | Item_1 | Cost_1 | Supplier_2 | Item_2 | Cost_2 | Supplier_3 | Item_3 | Cost_3 |
+----+------------+--------+--------+------------+--------+--------+------------+--------+--------+
|  1 |          2 | SyYh33 |   3.78 |          1 |   314d |   7.58 |          3 |   7433 |  15.22 |
|  2 |          3 |   5477 |  14.99 |          3 |   5658 |  28.49 |          2 | h23nfs |  68.99 |

任何指针都会很棒。尝试使用连接和MIN(),但我还没有能够返回所需的结果。希望有一位MySQL大师可以让我摆脱困境。提前致谢

2 个答案:

答案 0 :(得分:0)

规范化您的架构 - 否则您将不得不忍受这样的查询:

select f.ID,
    i1.Supplier as Supplier_1,
    i1.Item_1,
    i1.Cost_1,
    i2.Supplier as Supplier_2,
    i2.Item_2,
    i2.Cost_2,
    i3.Supplier as Supplier_3,
    i3.Item_3,
    i3.Cost_3
from (select distinct ID from following_table) f
join following_table i1 on i1.ID = f.ID and i1.Supplier = (
    select t.Supplier
    from following_table t
    where t.ID = i1.ID
    order by Cost_1 asc
    limit 1
)
join following_table i2 on i2.ID = f.ID and i2.Supplier = (
    select t.Supplier
    from following_table t
    where t.ID = i2.ID
    order by Cost_2 asc
    limit 1
)
join following_table i3 on i3.ID = f.ID and i3.Supplier = (
    select t.Supplier
    from following_table t
    where t.ID = i3.ID
    order by Cost_3 asc
    limit 1
)

http://sqlfiddle.com/#!9/04933/2

答案 1 :(得分:-1)

我认为你要找的是UNION来结合你的结果。

SELECT *
FROM your_table
WHERE Cost_1 = (SELECT MIN(Cost_1) FROM your_table)
UNION
SELECT *
FROM your_table
WHERE Cost_2 = (SELECT MIN(Cost_2) FROM your_table)
UNION
SELECT *
FROM your_table
WHERE Cost_3 = (SELECT MIN(Cost_3) FROM your_table)