Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php MySQL-数字比较_Php_Mysql_Database - Fatal编程技术网

Php MySQL-数字比较

Php MySQL-数字比较,php,mysql,database,Php,Mysql,Database,我在数据库中有两个字符串: "01, 02, 03, 04, 05, 06" 这是我的PHP生成的字符串: "02, 03, 04, 06, 07, 08" 我想在我的数据库中检查这些数字中哪些是相同的,以及有多少个。你需要将字符串拉到php中,在“,”上拆分(分解),然后进行数组相交以得到相同的数字,并使用count()查找有多少个 //php $phpstring ="02, 03, 04, 06, 07, 08"; //fix the query $row=mysql_fetch_a

我在数据库中有两个字符串:

"01, 02, 03, 04, 05, 06"
这是我的PHP生成的字符串:

"02, 03, 04, 06, 07, 08"

我想在我的数据库中检查这些数字中哪些是相同的,以及有多少个。

你需要将字符串拉到php中,在“,”上拆分(分解),然后进行数组相交以得到相同的数字,并使用count()查找有多少个

//php
$phpstring ="02, 03, 04, 06, 07, 08";

//fix the query
$row=mysql_fetch_array(mysql_query("SELECT mystring from mytable where something"));

$dbstring=$row['mystring'];

$dbarray=explode(', ' $dbstring);
$phparray=explode(', ',$phpstring);

$identicals=array_intersect($dbarray,$phparrray);

echo "there are ".count($identicals)." identical elements: ". implode(",",$identicals);

如果它作为字符串存储在数据库中,则在SQL查询中没有方法执行此操作。您最好编写一个自定义MySQL或获取所有行并在PHP脚本中处理它们,但这两种方法都是相对糟糕的解决方案,因为envolve处理表中的每一行。它可能会消耗时间和CPU,特别是如果它是一个大表

但是有解决这个问题的方法,你只需要使用这个表中正确的结构。你需要的是一对多的关系。例如,不采用这种结构:

| numbers
| "1, 2, 3, 4"
| "5, 6, 7, 8"
你可以这样做:

| group | number 
| 1     | 1
| 1     | 2
| 1     | 3
| 1     | 4
| 2     | 5
| 2     | 6
| 2     | 7
| 2     | 8
然后你可以做:

$sql = "SELECT
            `group`,
             COUNT(*),
             GROUP_CONCAT(`number` SEPARATOR ', ')
        FROM
            `table`
        WHERE
           `number` IN (2, 3, 4, 6, 7, 8)
        GROUP BY
           `group`
        ORDER BY
           COUNT(*) DESC
        LIMIT 1";

$res = mysql_query($sql);
$row = mysql_fetch_row($res);

echo "The group with most matches is the group {$row[0]}
      with {$row[1]} hits. The matching numbers were {$row[2]}.";

这是相当模糊的。首先,数据库模式是什么?生成第二个字符串的适用代码是什么?请尝试将这两个字符串放入一个以“,”作为分隔符的数组中。然后对它们进行排序和比较。您应该在问题中包含您自己尝试的代码