mysql如何从子串中计算值

时间:2017-09-11 17:11:11

标签: mysql mysqli

从水合值计算时,我遇到了一些麻烦, 这是我的查询

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.therapi, ',', n.n), ',', -1) value
FROM tbl_riwayat t CROSS JOIN 
(
  SELECT a.N + b.N * 10 + 1 n FROM 
  (
    SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 
    UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL 
    SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
    ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 
    UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL 
    SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n
  ) n
  WHERE n.n <= 1 + (LENGTH(t.therapi) - LENGTH(REPLACE(t.therapi, ',', '')))
  ORDER BY value

,这是结果

value
---------------
|Nodrop|
|Nodrop|
|Test1|
|Test2|   

我想像Nodrop = 2 Test1 = 1 Test2 = 1那样计算价值 请帮忙,非常感谢

1 个答案:

答案 0 :(得分:0)

试试这个:

 SELECT t1.value, COUNT(t1.value) FROM (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.therapi, ',', n.n), ',', -1) value
FROM tbl_riwayat t CROSS JOIN 
(
  SELECT a.N + b.N * 10 + 1 n FROM 
  (
    SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 
    UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL 
    SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
    ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 
    UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL 
    SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n
  ) n
  WHERE n.n <= 1 + (LENGTH(t.therapi) - LENGTH(REPLACE(t.therapi, ',', '')))
  ORDER BY value) t1 GROUP BY t1.value