sql从一个表中拆分逗号分隔的列表,并基于此列表打印第二个表中的内容

pinkon5k  于 2021-06-21  发布在  Mysql
关注(0)|答案(22)|浏览(913)

我有两张table, rooms 以及 utilities . 在名为 rooms 我有一个Column也叫 utilities . 此列存储引用表中ID的逗号分隔数字 utilities .
如何从 utilities 列,并将它们与 utilities 表,打印具有匹配ID的值作为输出值?
例子:
表:房间
|

4c8rllxm

4c8rllxm4#

     2              电视           
s4chpxco

s4chpxco5#

试试这个

SELECT r.Name,GROUP_CONCAT(u.Device) FROM rooms r
LEFT JOIN utilities u ON FIND_IN_SET(u.id,r.Utilities)>0
GROUP BY r.ID
quhf5bfb

quhf5bfb6#

     4           网络摄像机
irlmq6kh

irlmq6kh8#

     身份证            装置      
kqqjbcuj

kqqjbcuj12#

表:公用设施
|

ccgok5k5

ccgok5k514#

     身份证           姓名          公用事业     
qnakjoqk

qnakjoqk15#

我想打印这样的东西: Room1: Speakers, Smart TV, Web camera 到目前为止,我得到的是confroomreport.php:

<?php
 require_once("db.php");
 $util = $conn->getDeviceList();
 $arr = $conn->getConfRoomList();
?>

<table border='1'>
    <tr>
        <th>Room</th>
        <th>Utilities</th>
    </tr>
    <?php for( $i=0; $i < count($arr); $i++) {
    print_r  ("<tr>
     <td>".$arr[$i]['name']."</td>
     <td>".$arr[$i]['utilities']."</td>
     </tr>"); } ?>
</table>

而且在 db.php ```
public function getDeviceList()
{
$arr = array();
$statement = $this->conn->prepare("SELECT id, device from utilities order by device ASC");
$statement->bind_result($id, $device);
$statement->execute();
while ($statement->fetch()) {
$arr[] = [ "id" => $id, "device" => $device];
}
$statement->close();

      return $arr;
}

public function getConfRoomList()
{
$arr = array();
$statement = $this->conn->prepare("SELECT id, name, utilities from rooms order by name ASC");
$statement->bind_result($id, $name, $utilities);
$statement->execute();
while ($statement->fetch()) {
$arr[] = [ "id" => $id, "name" => $name, "utilities" => $utilities];
}
$statement->close();

  return $arr;

}

根据接受的解决方案编辑更新的代码:
我在db.php中添加了以下内容:

public function joinDevRoom()
{
$arr = array();
$statement = $this->conn->prepare("SELECT r.name,GROUP_CONCAT(u.device) FROM room r LEFT JOIN utilities u ON FIND_IN_SET(u.id,r.utilities)>0 GROUP BY r.id");
$statement->bind_result($id, $utilities);
$statement->execute();
while ($statement->fetch()) {
$arr[] = [ "id" => $id, "utilities" => $utilities];
}
$statement->close();

 return $arr;

}

这是我更新的confroomreport.php:

相关问题