2016-06-13 86 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