2014-02-25 79 views
0

我有一些數據以這種格式排列。與家族層次結構/佈局相關的MySQL查詢

SR | NAME   | FATHER NAME  | ADDRESS | GROUP 
1 | SAM FISHER  | MR. KINGSLEY  | PARK VIEW | USER 
2 | JOHN FISHER  | MR. KINGSLEY  | PARK VIEW | USER 
3 | KADINAL   | MR. BEN   | PARK VIEW | USER 

這裏1 & 2金斯利先生的孩子有相同的地址和組。 但第三個不是金斯利先生的孩子,但有同樣的地址和組。

我需要這樣的查詢,使我能得到這樣的數據報告同級。

輸出應該是這樣的

兄弟報告

SR | NAME   | FATHER NAME  | ADDRESS | GROUP 
1 | SAM FISHER  | MR. KINGSLEY  | PARK VIEW | USER 
    JOHN FISHER 
------------------------------------------------------------- 
2 | KADINAL   | MR. BEN   | PARK VIEW | USER 

現在我使用MySQL查詢

SELECT id, fat_name, sec, address, class, mobile, 
    GROUP_CONCAT(DISTINCT stu_name order by class ASC SEPARATOR ', ') stu_name, 
    GROUP_CONCAT(DISTINCT class order by class ASC SEPARATOR '<br>') class, 
    GROUP_CONCAT(DISTINCT sec order by class ASC SEPARATOR '<br>') sec, 
    GROUP_CONCAT(DISTINCT address order by class ASC SEPARATOR '<br>') address, 
    GROUP_CONCAT(DISTINCT adm_no order by class ASC SEPARATOR '<br>') adm_no 
FROM student 
where class <> 'OUT' and session='".$session."' 
GROUP BY fat_name 
order by class DESC 

PHP:

<?php 
echo "<table id='testTable'><tr>"; 
$count = 1; 

while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) 
    { 
    extract($row); 
    $stu_name = $row['stu_name']; 
    $fat_name = $row['fat_name']; 
    $address = $row['address']; 
    echo "<td style='width:33%;'><br/>" . $stu_name . "<br/>" . $fat_name . "<br/>" . $address . "<br/><br‌​/></td>"; 
    if ($count++ % 3 == 0) 
     { 
     echo "</tr><tr>"; 
     } 
    } 

echo "</tr></table><br/><br/><br/>"; 

它也有一個條件,如果約翰費舍爾與山姆費舍爾一起被包括在頂端,那麼約翰將不會在底部重複。

+0

不知道你可以查詢做到這一點,但它使用PHP函數是可能的。 –

+0

有什麼想法@ICanHasCheezburger – alleged

+0

你可以粘貼你如何打印上述報告的代碼? –

回答

0

嘗試(未經測試):

如果
echo "<table id='testTable'><tr>"; 
$count = 1; 
$keep_track = array(); //array to keep track of father names already displayed 
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) 
{ 
    extract($row); 
    $stu_name = $row['stu_name']; 
    $fat_name = $row['fat_name']; 
    $address = $row['address']; 

    //over here we check if the father name has been displayed already, 
    //initially it will be false 
    if(array_key_exists($fat_name,$keep_track)){ 
     //if it has been mentioned, skip all fields and display only 'stu_name' 
     echo "<td style='width:33%;'><br/>" . $stu_name . "<br/><br/><br/><br‌​/></td>"; 
    } 
    else 
    { 
     //if it hasn't been displayed, show all fields 
     echo "<td style='width:33%;'><br/>" . $stu_name . "<br/>" . $fat_name . "<br/>" . $address . "<br/><br‌​/></td>"; 
     //record father name in array so that in next loop 
     //it is not displayed again 
     $keep_track[] = $fat_name; 
    } 
    if ($count++ % 3 == 0) 
    { 
     echo "</tr><tr>"; 
    } 

} 

echo "</tr></table><br/><br/><br/>"; 
1

如果「FATHER NAME」值相同的記錄也具有相同的ADDRESS和GROUP值,則應考慮重新設計您的表並將「父親名稱」,ADDRESS和GROUP放在單獨的表中,並將「Name」另一張國外參考表。否則,對於你想要達到的目標是沒有意義的。