gpt4 book ai didi

php - 如何在 codeIgniter (mysql) 中按 'name + 0' 排序

转载 作者:行者123 更新时间:2023-11-29 04:36:57 24 4
gpt4 key购买 nike

我在 MySQL 数据库中有一个表,如下所示:

id | name
1 | 1 some words
2 | 2 some other words
3 | 1.1 some other words
...
10 | 10 some other words

如果我使用以下方法对表格进行排序:

$this->db->select('*')
->order_by('name', 'ASC')
->get('table_name');

我按以下顺序收到表格:

id | name
1 | 1 some words
3 | 1.1 some other words
10 | 10 some other words
...
2 | 2 some other words

但我实际上想按以下顺序接收表格:

id | name
1 | 1 some words
3 | 1.1 some other words
2 | 2 some other words
...
10 | 10 some other words

这可以使用以下 SQL 语句:

SELECT * FROM database_name.table_name ORDER BY name + 0 ASC;

但是如果我像这样使用 codeIgniters 查询构建器,我会得到一个数据库错误:

$this->db->select('*')
->order_by('name + 0', 'ASC')
->get('table_name');

请注意,在我的情况下,不可能将数字存储在不同的列中或按 ID 排序。

那么有没有办法让这个 SQL 语句在 CodeIgniters 查询构建器中工作?

SELECT * FROM database_name.table_name ORDER BY name + 0 ASC;

提前致谢

编辑:对于混淆,我感到非常抱歉,但 '.'在 1.1 中并不意味着是一个 float ,而是像一个点:1.1.1、1.1.2、1.1.3我找到了一个使用@Marc B 解决方案的解决方案,并将其放入查询构建器中,如下所示:

$query = $this->db->select('name+0  AS name', FALSE)           
->order_by('name', 'ASC')
->get('table_name');

非常感谢大家的回答

最佳答案

我认为你应该先按数字再按文字排序。

演示:

SET @str := '1.1 some other words';

SELECT
SUBSTRING_INDEX(@str,' ',1)+0 AS numberPart,
SUBSTRING_INDEX(@str,SUBSTRING_INDEX(@str,' ',1),-1) AS textPart;

输出:

numberPart     textPart
1.1 some other words

这是完整的查询:

SELECT 
*
FROM database_name.table_name
ORDER BY SUBSTRING_INDEX(name,' ',1)+0,
SUBSTRING_INDEX(name,SUBSTRING_INDEX(name,' ',1),-1);

See demo

或者您可以尝试将数字字符串转换为十进制类型。

See Demo

关于php - 如何在 codeIgniter (mysql) 中按 'name + 0' 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39025922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com