0

我有三个 PHP 数组,它们都有相同的两个键:pIdname. 数组的名称是added, deleted& updated

我要比较的表如下所示:

id
relationId
pId
name
changeType

这些行按关系 ID 分组,每个关系 ID 可能有多个 pId 和名称对。changeType可以是added,deletedupdated.

我想要的是能够运行单个查询来检查与三个数组完全匹配的一组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。

4

1 回答 1

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();
?>
于 2013-08-05T12:17:33.870 回答