MYSQL一对多关系推入数组

时间:2017-06-22 11:21:32

标签: php mysql json left-join

我正在查询DB

    $query="SELECT com.id, com.name, ctx.LastName, ctx.FirstName, com.company_phone,addr.City, addr.Street ";
    $query.="FROM Connections as con ";
    $query.="LEFT JOIN Companies as com on con.company_id = com.id ";
    $query.="LEFT JOIN Contacts as ctx on con.contact_id = ctx.id ";
    $query.="LEFT JOIN addresses as addr on addr.id = com.Legal_address ";
    if($value['db']=='companies') $query.="WHERE LOWER(com.".$value['model'].") RLIKE LOWER('".$value['val']."')";
    else if($value['db']=='contacts') $query.="WHERE LOWER(ctx.FirstName) RLIKE LOWER('".$value['val']."') OR LOWER(ctx.LastName) RLIKE LOWER('".$value['val']."')";
    else if($value['db']=='addresses') $query.="WHERE LOWER(addr.City) RLIKE LOWER('".$value['val']."') OR LOWER(addr.Street) RLIKE LOWER('".$value['val']."')";

然后将结果发送回客户端。结果我可以看到,例如:

[
 {
  id:1,
  name: google,
  contact: Smith,
  ....
 },
 {
  id:1,
  name: google,
  contact: Black,
  ....
 },
 {
  id:2,
  name: microsoft,
  contact: Walker,
  ....
 }
 ....

但是我想看到没有重复的行,但是有一对多关系的数组。像第二个例子:

[
 {
  id:1,
  name: google,
  contact: [Smith, Black],
  ....
 },

 {
  id:2,
  name: microsoft,
  contact: Walker,
  ....
 }
 ....

我对SQL的了解非常糟糕。我已被告知WHERE + JOIN心情不好。因此可以更改我的查询,以便它在第二个示例中。

P.S。当我将响应发送回客户端时,我用json格式的结构编写了两个数组。

2 个答案:

答案 0 :(得分:1)

您可能需要获取数据并制作所需的数组。

    $data = array();
    foreach ($result as $fields) {
        $key = $fiels['name']; // or $item['info_id']
        if (!isset($data[$key])) {
            $data[$key] = array();
        }

        $data[$key][] = $field;
    }

// Build your table with the new $data array

这只是一个例子。正如它所指出的,如果您的名称字段不是唯一的,则需要在唯一键上构建阵列。与此并无太大区别,因为您可能只需将$field['name']的实例更改为$field['info_id']

答案 1 :(得分:1)

$query="SELECT com.id, com.name, CONCAT('[',GROUP_CONCAT(ctx.LastName),']') AS contact, ctx.LastName, ctx.FirstName, com.company_phone,addr.City, addr.Street ";
$query.="FROM Connections as con ";
$query.="LEFT JOIN Companies as com on con.company_id = com.id ";
$query.="LEFT JOIN Contacts as ctx on con.contact_id = ctx.id ";
$query.="LEFT JOIN addresses as addr on addr.id = com.Legal_address ";
if($value['db']=='companies') $query.="WHERE LOWER(com.".$value['model'].") RLIKE LOWER('".$value['val']."')";
else if($value['db']=='contacts') $query.="WHERE LOWER(ctx.FirstName) RLIKE LOWER('".$value['val']."') OR LOWER(ctx.LastName) RLIKE LOWER('".$value['val']."')";
else if($value['db']=='addresses') $query.="WHERE LOWER(addr.City) RLIKE LOWER('".$value['val']."') OR LOWER(addr.Street) RLIKE LOWER('".$value['val']."')";
$query .= " GROUP BY com.id ";

我从输出JSON中将LastName列假设为Contact