MYSQL订购子字符串计数

时间:2014-03-10 05:14:22

标签: php mysql

我想通过子串的计数来命令我的查询。

表:

id shop_update

1  a,b,c
2  a,b
3  c
4  a,'',c

我只是按计数来订购

id  shop_update count
 1   a,b,c       3
 2   a,b         2
 3   c           1
 4   a,'',c      2

我的查询是

$this->db->select("*,LENGTH(shop_update) - LENGTH(REPLACE(shop_update,',','')) AS counts");
$this->db->order_by("counts","DESC");
$this->db->from('at_shop');

但它只在计数

中返回0
 id  shop_update count
     1   a,b,c       0
     2   a,b         0
     3   c           0
     4   a,'',c      0

我的问题是LENGTH(REPLACE(REPLACE(shop_update,',',''),'''',''))它的运行空间如LENGTH(REPLACE(REPLACE(shop_update,', ',''),'''',''))

(在查询中添加空格(','),但实际代码中没有空格)

请看差异 有什么帮助吗?

3 个答案:

答案 0 :(得分:2)

只需在查询中使用此功能,即可获得正确的计数:

LENGTH(REPLACE(REPLACE(shop_update,',',''),"' '",''))

请参阅此处的相同工作示例:http://www.sqlfiddle.com/#!2/fa7a5/7

答案 1 :(得分:1)

SELECT * 来自tablename 按长度排序(更新(shop_update,',',''))DESC

答案 2 :(得分:0)

您可以使用此命令

SELECT id,shop_update,LENGTH(replace(shop_update,"''","")) as count FROM table_name ORDER BY  count desc