2013-08-04 92 views
0

我有三個PHP數組,它們都具有相同的兩個鍵:pIdname。陣列的名稱是added,deleted & updated將數據庫表中的分組值與關聯數組進行比較

我想看起來像這樣比較表:

id 
relationId 
pId 
name 
changeType 

該行由relationId分組,並且有可能是每relationId多個PID &名對。 changeType可以是added,deletedupdated

我想要的是能夠運行來檢查,如果一組pId 雙(其中changeType數組名稱相匹配),這三個陣列完全匹配,在表中存在一個單一的查詢並返回relationId

這可能嗎?


表:

+--------+----------------+---------+---------------+----------------+ 
| **id** | **relationId** | **pId** | **name** | **changeType** | 
+--------+----------------+---------+---------------+----------------+ 
| 1 |  1  | 1 |  Smith  |  added  | 
+--------+----------------+---------+---------------+----------------+ 
| 2 |  1  | 2 |  John  |  updated | 
+--------+----------------+---------+---------------+----------------+ 
| 3 |  1  | 3 |  Dexter |  deleted | 
+--------+----------------+---------+---------------+----------------+ 
| 4 |  1  | 4 | Heisenberg |  added  | 
+--------+----------------+---------+---------------+----------------+ 
| 5 |  2  | 4 | Heisenberg |  added  | 
+--------+----------------+---------+---------------+----------------+ 
| 6 |  2  | 3 |  Dexter |  updated | 
+--------+----------------+---------+---------------+----------------+ 
| 7 |  2  | 3 | Dexter Morgan |  updated | 
+--------+----------------+---------+---------------+----------------+ 

PHP陣列:

$added = array(
[1] = array(
    pId => 4, 
    name => 'Heisenberg' 
) 
) 

$deleted = array(
//Empty 
) 

$updated = array(
[1] = array(
    pId => 3, 
    name => 'Dexter' 
) 
[2] = array(
    pId => 3, 
    name => 'Dexter Morgan' 
) 
) 

當使用該陣列查詢返回的relationId應該爲2

+0

這是一個有點抽象。你能顯示一些代碼和一些示例數據嗎? –

+0

是的,這很難解釋,但我發佈了一個例子。 –

回答

0

我解決了這個通過比較在表格中使用GROUP_CONCAT從數組中得到一個內爆字符串。由於您通常不能在WHERE條款中使用GROUP_CONCAT,因此我必須使用FROM子句做一個解決方法。

<?php 
    $s = ''; 
    foreach($updated as $u){ 
     $s .= $u['pId'] . $u['name'] . 'updated,'; 
    } 
    foreach($deleted as $d){ 
     $s .= $d['pId'] . $d['name'] . 'deleted,'; 
    } 
    foreach($added as $a){ 
     $s .= $a['pId'] . $a['name'] . 'added,'; 
    } 

    //remove last comma 
    $s = rtrim($s, ','); 

    $stmt = $mysqli -> prepare(" 
    SELECT 
     relationId 
     FROM (
      SELECT 
       relationId, 
       GROUP_CONCAT(pId, name, changeType ORDER BY changeType DESC, id ASC) AS personConcat 
      FROM 
       persons 
      GROUP BY relationId 
     ) x 
     WHERE personConcat = ? 
    "); 

    $stmt -> bind_param('s', $s); 
    $stmt -> execute(); 
?> 
相關問題