2016-06-13 88 views
0

我正在爲自己創建一個CRM。我的數據庫包含四個表格。在我的網站的一部分中,我希望while循環連接到[聯繫人]的所有[註釋]和[任務]。顯示多個sql查詢並按時間戳排序

[鏈接](鏈接接觸到的任務)

'id' 'contact_id' 'task_id' 
'1' '1' '1' 

[聯繫方式]

'id' 'contact_name' 
'1' 'Robert' 

[任務]

'id' 'description' 'due_date' 
'1' 'Call to say hello' '2016:06:13' 

【注意事項】(注直接鏈接到接觸)

'id' 'contact_id' 'text' 'date_entered' 
'1' '1' 'I met Robert on the weekend.' '2016:06:12' 

我現在唯一知道的就是創建兩個單獨的查詢。一個選擇和顯示任務信息...

$contact_id_for_example = '1' 
$find_the_link = $mysqli->query("SELECT * FROM link WHERE contact_id = '$contact_id_for_example'"); 

if($find_the_link->num_rows != 0){ 

     while($link_rows = $find_the_link->fetch_assoc()) 
     { 

      $link_task_id = $link_rows['task_id']; 

      $find_the_task = $mysqli->query("SELECT * FROM task WHERE id = '$link_task_id' ORDER BY due_date"); 

       if($find_the_task->num_rows != 0){ 

        while($task_rows = $find_the_task->fetch_assoc()) 
        { 

         $task_description = $task_rows['description']; 

         echo '<li>'.$task_description.'</li>'; 

        } 
     } 

..和一個顯示音符信息..

$note_select = $mysqli->query("SELECT * FROM note WHERE contact_id = '$contact_id_for_example' ORDER BY 'date_entered'"); 

if($note_select->num_rows != 0){ 

    while($note_rows = $note_select->fetch_assoc()) 
    { 

     $note_text = $note_rows['text']; 

     echo '<li>'.$note_text.'</li>'; 

    } 
} 

我的方法的問題是,上面的代碼將打印所有的首先匹配任務,然後是下面的所有註釋。即使第一張筆記在任務完成之前已輸入/到期,他們仍會在任務完成後打印。

我查看了JOINS,並沒有看到在這種情況下如何工作,因爲[link]表互連了[contact]和[task]表。

我也搜遍了這個網站和其他人,並注意到Multiple Queries.,但從我迄今爲止讀過的這也不能解決問題。

這裏是我的嘗試:

$test_contact_id = '1068'; 

$query = "SELECT * FROM link WHERE contact_id = '$test_contact_id';"; 
    $storing_link = $query->num_rows; 
    $find_task_id = $storing_link->fetch_fields(); 
    $find_task_id->task_id; 
$query .= "SELECT * FROM task WHERE id = '$find_task_id';"; 
    $storing_task = $query->num_rows; 
    $find_task_description = $storing_task->fetch_fields(); 
    $task_description->text; 
$query .= "SELECT * FROM note WHERE contact_id = '$test_contact_id';"; 
    $storing_note = $query->num_rows; 
    $find_note_text = $storing_note->fetch_fields(); 
    $note_text = $find_note_text->text; 

if($mysqli->multi_query($query)){ 

    echo '<p>'.$task_description.' :: '.$note_text.'</p>'; 

} 

回答

2

JOIN s爲正是你想要的。您只需要一些邏輯即可檢測到在記錄集之間移動的時間。例如一個簡單的狀態機:

SELECT ... 
ORDER BY table1.foo, table2.bar, table3.baz 

$prev1 = $prev2 = $prev3 = null; 
while($row = fetch()) { 
    if ($row['table1.foo'] != $prev1) { 
    start a new table1 output 
    $prev1 = $row['table1.foo']; 
    } 
    ... repeat for tables 2&3, 
    ... output "core" data 
} 
+0

謝謝你我會研究這個並返回。 – Bjaeg