doushan7077 2017-11-09 15:03
浏览 37

获取具有它们之间关系的行

I have table in my database containing relations between clients companies. Below is just a part from the existing table.

+----+---------+---------+
| ID | Client1 | Client2 |
+----+---------+---------+
| 18 |     250 |      77 |
| 19 |     250 |     317 |
| 13 |     317 |      12 |
|  5 |      23 |      12 |
+----+---------+---------+

When seeing client 250 I can show also clients 77 and 317. I want to be able to fetch the ids of the other clients in the chain so that when my user opens client 250 to see the ids of 77, 317, 12 and 23. Is there a way to fetch all the ids with one mysql query or I should have some other data processing. Below is the query and some checks for the current situation:

$sql = "SELECT cc.Id, cc.Client1Id, cc.Client2Id, cc.Note
            FROM ClientConnections as cc
            WHERE cc.Client1Id  = ? OR cc.Client2Id = ?";
            $stmt = $this->db -> prepare($sql);
            $stmt -> bind_param('ii', $id, $id);
            $stmt -> execute();
            $stmt -> bind_result($connectionId, $client1Id, $client2Id, $note);
            $stmt -> store_result();

        while($stmt -> fetch()){

            //if found client has the same id as the current client
            if ($client1Id == $id) {
                $clientId = $client2Id;
            }elseif ($client2Id == $id) {           
                $clientId = $client1Id;
            }

            $name = $this->getClient($clientId); //getting client info

            $array[] = array(
                'id' => $connectionId,
                'client_id' => $clientId,
                'name' => $name['name'],
                'payment_status' => $name['payment'],
                'note' => $note
            );

        }

If there is a query which can done the job will be perfect, but if there isn't I'll be happy someone to give me just an idea how to do that. Maybe a recursion? I'm stuck.

  • 写回答

1条回答 默认 最新

  • douhang5460 2017-11-09 15:35
    关注

    Try this answer.

    The guy is using GROUP_CONCAT to Group the rows. You can use it on your query to group your rows based on Client 1.

      SELECT k.id, GROUP_CONCAT(d.value ORDER BY d.name separator ' ')
      FROM keywords AS k
      INNER JOIN data as d ON k.id = d.id
      GROUP BY k.id
    

    The problem is that he is using two tables to do that, so you can either split your tables or you can do INNER JOIN (SELECT .. on the same table.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?