我想从具有相同行的表中检索最小值和对应的列名。请参阅查询以获取最小值:
SELECT least(supplier1,supplier2,supplier3,supplier4,supplier5) AS minValue
FROM
priceTable
WHERE partno='OL0003';
上面产生20。现在,我想选择20和列名,在这种情况下为Supplier1。我需要添加什么查询,或者有重构代码可以立即帮助您完成此操作。我正在使用mysql
答案 0 :(得分:3)
之后,您需要一个case
表达式:
SELECT least(supplier1, supplier2, supplier3, supplier4, supplier5) AS minValue,
(CASE least(supplier1, supplier2, supplier3, supplier4, supplier5)
WHEN supplier1 THEN 'supplier1'
WHEN supplier2 THEN 'supplier2'
WHEN supplier3 THEN 'supplier3'
WHEN supplier4 THEN 'supplier4'
WHEN supplier5 THEN 'supplier5'
END) as column_name_for_min
FROM priceTable
WHERE partno = 'OL0003';
如果您更好地组织数据,这将更加简单。您应该有一个表格PartSuppliers
,每个零件和每个供应商都有一行。
然后,您可以通过各种方式获得最少的价值,例如:
select ps.*
from partsuppliers ps
where ps.cost = (select min(ps2.cost)
from partsuppliers ps2
where ps2.partno = ps.partno
);