2016-03-24 102 views
2

當我想從數據庫分組結果時,我有這個問題。我必須表1)設備和2)device_groups。我使用INNER JOIN來獲取相關數據。從數據庫和顯示PHP和MYSQL組結果

$mysqli = new mysqli('localhost', 'name', 'pass', 'tbl'); 


$qry = " 
     SELECT g.id as groupId, g.name as groupName, d.device_id 
     FROM librenms.devices as d 
     INNER JOIN librenms.device_groups as g 
       ON d.hostname LIKE CONCAT('%', mysql.SPLIT_STR(g.pattern, '\"', 2), '%') 
     WHERE g.pattern LIKE '_devices.hostname%' 
     ORDER BY g.id 
"; 


$qid = $mysqli->query($qry); 

下面的代碼看起來是這樣的:

<table> 
<tr> 
    <th>Group Name</th> 
    <th>Device ID</th> 
</tr> 
<?php while($row = $qid->fetch_assoc()){ 
    $deviceId = split(",",$row["device_id"]); 
?> 
    <tr> 
     <td><?php echo $row["groupName"] ?> </td> 
     <td><?php echo $deviceId[0]; array_shift($deviceId) ?></td> 
    </tr> 
    <?php foreach($deviceId as $device){ ?> 
     <tr> 
      <td></td> 
      <td><?php echo $device ?></td> 
     </tr> 
    <?php } ?> 
<?php } ?> 
</table> 

而我得到的結果是這樣的:

Group Name | Device ID 
group1  | 154 
group1  | 155 
group1  | 156 
group2  | 157 
group2  | 158 
group2  | 159 
group3  | 160 
group3  | 161 

所以,我的問題是,什麼是好辦法,以組日期groupName或groupId,並像下表中那樣顯示它?正如你所看到的,我想讓羣組名稱只被打印一次,屬於這個羣組的所有設備都將打印出與羣組名稱的關係。

Group Name  | Device ID 
........................... 
    group1  | 154 
       | 155 
       | 156 
........................... 
    group2  | 157 
       | 158 
       | 159 
........................... 
    group3  | 160 
       | 161 

回答

0

預期的結果可以通過在user variable中記錄上一個組名來實現。

如下更改$qry

SELECT 
    g.id as groupId, 
    IF(g.name = @last_name, '', g.name) as groupName, 
    d.device_id, 
    @last_name := g.name 
FROM librenms.devices as d 
INNER JOIN librenms.device_groups as g 
     ON d.hostname LIKE CONCAT('%', mysql.SPLIT_STR(g.pattern, '\"', 2), '%') 
CROSS JOIN (SELECT @last_name := '') param 
WHERE g.pattern LIKE '_devices.hostname%' 
ORDER BY g.id