count在单行中用逗号分隔的唯一ID

时间:2014-06-27 08:18:28

标签: php mysql

我在mysql中有以下详细信息

   user_id                  follow_user_id                                                    
   1                      2,3,3,3,3
   5                      1,2,3,3,3,3
   6                      1,2,3,3,3,3  

我编写以下代码以获取如下唯一代码:

SELECT LENGTH( follow_user_id ) - LENGTH( REPLACE( follow_user_id, ',', '' ) ) +1 AS no_of_follow FROM follow WHERE user_id =1;

但它提供了结果:6 我需要完全独特的行:即:4

请帮助我 谢谢&问候 提前

4 个答案:

答案 0 :(得分:1)

除了DB设计问题之外,您可以在将行提取到$ result后在PHP中使用:

count(array_unique(explode(",",$result["follow_user_id")));

答案 1 :(得分:1)

$ query =" SELECT follow_user_id FROM跟随WHERE user_id ='"。$ _ POST [' user_id']。"' &#34 ;; $ query_run =的mysql_query($查询); $ row = mysql_fetch_assoc($ query_run);

$ count = count(array_unique(explode(",",$ row [' follow_user_id'])));

$计数;

答案 2 :(得分:0)

这更好更快;)

count(array_flip(explode(",", $result["follow_user_id")));

答案 3 :(得分:0)

或者在SQL中执行: -

SELECT COUNT(DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(follow_user_id, ',', units.i + tens.i * 10), ',', -1) AS col1)
FROM sometable
CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)units
CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)tens
WHERE user_id = 1

(应对最多100个逗号分隔值)。

但是,通过正确规范化的数据库设计,这将变得更加容易