将数据库表中的分组值与关联数组进行比较

时间:2013-08-04 16:25:33

标签: php mysql relational-database associative-array

我有三个PHP数组,它们都有相同的两个键:pIdname。数组的名称为addeddeleted& updated

我要比较的表格如下:

id
relationId
pId
name
changeType

行按关系Id分组,可能有多个pId&每个relationId的名称对。 changeType可以是addeddeletedupdated

我想要的是能够运行一个查询,检查是否有一组pId& name对(其中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。

1 个答案:

答案 0 :(得分:0)

我通过比较表中的GROUP_CONCAT数组中的内爆字符串来解决这个问题。由于您无法在GROUP_CONCAT子句中正常使用WHERE,因此我必须使用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();
?>