2

My database column is a varchar(25) datatype with values 1 1/2", 1/2", 3", and 4" representing hose diameters for a fire station. The issue I am having is that the following code spits out the hose diameters in the above order in the database when I want to order in ascending order, meaning I want "1/2, 1 1/2, 3, 4" not with the 1 1/2 at the front. IS there a way to do this in SQL with fractional data values for my varchar datatype?

// Select hose locations from fire database
$query = "SELECT hose_diameter FROM hose_diameter ORDER BY hose_diameter";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

//FETCH ROWS
if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        print "<option value=\"".$row['hose_diameter']."\">".$row['hose_diameter']."</option>";
    }
}
4

1 回答 1

1

这是一种方法。它只是摆脱了第一个排序的“1/2”,然后将其添加回:

order by replace(diam, '1/2', ''), diam

当然,这不容易推广到其他分数。

另一种方法是在前面添加'0'一个字符时在前面添加一个字符'/'

order by (case when diam like '_/%' then '0'+diam else diam end)

最后,您可以将直径作为数字查找表:

SELECT hd.hose_diameter
FROM hose_diameter hd left outer join
     (select '1/2' as hose_diameter, 0.5 as units union all
      select '1 1/2', 1.5 union all
      select '3', 3 union all
      select '4', 4
     )diams
     on hd.hose_diameter = diams.hose_diameter
ORDER BY diams.units;

我其实更喜欢这种方法,因为意图很明确。

编辑:

我不明白评论。我刚刚测试了这段代码:

with hose_diameter as (
      select '1/2' as diam union all
      select '1 1/2' union all
      select '3'
     )
SELECT hd.diam
FROM hose_diameter hd left outer join
     (select '1/2' as hose_diameter, 0.5 as units union all
      select '1 1/2', 1.5 union all
      select '3', 3 union all
      select '4', 4
     ) diams
     on hd.diam = diams.hose_diameter
ORDER BY diams.units;

它返回:

1/2
1 1/2
3

我测试了第一个版本,它返回相同的顺序。还有第二个版本。

于 2013-07-08T18:42:53.853 回答