2013-10-30 37 views
-4

我有兩個字符串,這樣在數據庫:MySQL的 - 數字比較

"01, 02, 03, 04, 05, 06" 

,這是我的PHP生成的字符串:

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

我要檢查,在我的數據庫,其中這些數字是相同的,多少。

+0

這是非常模糊的。首先,數據庫模式是什麼以及生成第二個字符串的適用代碼是什麼? – admdrew

+0

嘗試將2個字符串放入數組中,''作爲分隔符。然後對它們進行分類和比較你應該在你的問題中包含你自己嘗試的代碼 –

回答

1

你需要拉出串入你的php,分裂(爆炸)上「」然後做一個array_intersect得到相同的,和計數()找到多少

//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); 
0

如果它作爲字符串存儲在數據庫中,沒有辦法在SQL查詢中執行此操作。您最好的機會是編寫自定義MySQL FUNCTION或獲取所有行並將它們處理到您的PHP腳本中,但兩者都是相對較差的解決方案,因爲它會處理表中的每一行。它可能既耗時又耗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]}.";