简体   繁体   English

将查询返回的数据库列值排序为数值

[英]Sorting database column values returned from query as a numeric value

Issue : I am writing a query that involves a count() operation on a column but returns the count in the string format. 问题 :我正在编写一个涉及列上count()操作的查询,但返回字符串格式的计数。 As a result the sorting on the front end is messed up. 结果,前端的分类混乱了。

Details: I am writing the following query in Zend: 详细信息:我在Zend中编写以下查询:

$select = $this->select()
        ->setIntegrityCheck(false)
        ->from(array('s' => 'student'),
            array('s.id', 
            'start_date' => new Zend_Db_Expr("date(s.start_date)"), 
            ))
        ->joinLeft(array('ps' => 'pstudent'), 
                's.id = ps.st_id',
                array('pscount' => new Zend_Db_Expr('count(ps.st_id)')  ))
        ->where('ps.status = "phd"');

$result = $this->getAdapter()->fetchAll($select);

This query returns me the pscount by using the Zend_Db_Expr (count(ps.st_id)) . 该查询返回我pscount使用Zend_Db_Expr (count(ps.st_id)) At a later point in code I encode this data to json format and return to the front end. 在代码的稍后阶段,我将此数据编码为json格式并返回到前端。 Since the data from db comes as a string (ie pscount is a string), when I sort on the front end on pscount column of the grid, I get the following sequence. 由于来自db的数据以字符串形式出现(即pscount是一个字符串),当我在网格的pscount列的前端排序时,我得到以下序列。

1 1
10 10
100 100
11 11
12 12
13 13

However,I want it to sort by numeric value so the output is: 但是,我希望它按数值排序,因此输出为:

1 1
10 10
11 11
12 12
13 13
100 100

I tried writing the Zend_Db_Expr as new Zend_Db_Expr('cast(count(ps.study_id) as signed)') but there is no change in the results. 我尝试将Zend_Db_Expr写为new Zend_Db_Expr('cast(count(ps.study_id) as signed)')但结果没有变化。 I cannot use an order by in the query as well due to application requirements. 由于应用程序的要求,我也不能在查询中使用order by The only other option is if I traverse through the $result and then do a (int) type conversion in php code. 唯一的另一个选择是如果我遍历$result然后在php代码中进行(int)类型转换。 However that is the last option. 然而,这是最后一个选择。 I would prefer to do this in mysql query so that I do not have to traverse through the results unnecessarily. 我更喜欢在mysql查询中执行此操作,以便我不必不必要地遍历结果。

Any help is really appreciated. 任何帮助都非常感谢。

Just get it as an array of strings and use sort($someArray, SORT_NUMERIC) . 只需将其作为字符串数组并使用sort($someArray, SORT_NUMERIC) This will sort them as if they were numbers. 这会将它们分类为数字。

If you need to sort complex objects, use usort() with a comparison function. 如果需要对复杂对象进行排序,请使用带有比较函数的usort()。

I don't believe you can order results inside mysql without using order by . 我不相信你可以在不使用order by情况下在mysql中订购结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM