如何执行按JSON类型列排序的SQL查询


How to perform a SQL query that orders by a column of type JSON?

我正在使用POSTGRESQL数据库,我需要通过JSON类型的列订购。这是我得到的错误:

ERROR: could not identify an ordering operator for type json
LINE 1: SELECT * FROM "field" "t" ORDER BY "t"."brand" LIMIT 10

是否可以按JSON数据类型排序?有什么解决办法吗?

表字段:

  • field_id INT
  • 名称
  • type INT
  • 品牌JSON
下面是我的代码:
$sql = 'SELECT * FROM "field" "t" ORDER BY "t"."brand"';      
$data = Yii::app()->db->createCommand($sql);
$result = $data->queryAll();

为此需要json访问器。从PG 9.2开始,没有内置的:

http://www.postgresql.org/docs/9.2/static/functions-json.html

PG 9.3将提供您需要的功能:

http://www.postgresql.org/docs/9.3/static/functions-json.html

同时,你可以在plperl中编写一个访问器方法,或者安装一个扩展:

https://github.com/theirix/json_accessors