2012-05-05 27 views
0

我下面的代碼連接5個表,然後假設按date_timed_added排序。查詢工作完美,如果我只加入4個表。出於某種原因,在第四張桌子後,它給我提出了問題。問題在於它會先排序並顯示第五個表格,然後再進行其他操作。我如何解決它,以便通過查詢所有其他表正確地對date_time_added進行排序?如何正確使用Order BY?

//$sid is a variable that is drawn from DB 

$sql = "select `client_visit`.`visit_id`, `client_visit`. 
`why_visit`, `client_visit`.`date_time_added`, `client_visit`. 
`just_date`, `client_visit`.`type` from `client_visit` where 
`client_visit`.`system_id` = '$sid' and `client_visit`. 
`added_by` = '$sid' 
UNION 
select `client_notes`.`note_id`, `client_notes`.`note_name`, 
`client_notes`.`date_time_added`, `client_notes`.`just_date` 
, `client_notes`.`type` from `client_notes` where `client_notes`. 
`added_by` = '$sid' 
UNION 
select `client_conditions`.`med_id`, `client_conditions`.`med_name`, 
`client_conditions`.`date_time_added`, `client_conditions`.`just_date`,  
`client_conditions`.`type` from `client_conditions` where 
`client_conditions`.`system_id` = '$sid' and `client_conditions`. 
`added_by` = '$sid' 
UNION 
select `client_stats`.`stat_test_id`, `client_stats`.`stat_why`, 
`client_stats`.`date_time_added`, `client_stats`.`just_date`, 
`client_stats`.`type` 
from `client_stats` where `client_stats`.`system_id` = '$sid' 
and `client_stats`.`added_by` = '$sid' 
UNION 
select `client_documents`.`doc_id`, `client_documents`.`doc_name`, 
`client_documents`.`date_time_added`, `client_documents`.`just_date`, 
`client_documents`.`type` from `client_documents` where `client_documents`. 
`system_id` = '$sid' and `client_documents`.`added_by` = '$sid' 
ORDER BY `date_time_added` DESC LIMIT $startrow, 20"; 

$query = mysql_query($sql) or die ("Error: ".mysql_error()); 

$result = mysql_query($sql); 

if ($result == "") 
{ 
echo ""; 
} 
echo ""; 


$rows = mysql_num_rows($result); 

if($rows == 0) 
{ 

} 
elseif($rows > 0) 
{ 
while($row = mysql_fetch_array($query)) 
{ 

//Just using these two variables i can display the same row info 
//for all the other tables 

$stuffid = htmlspecialchars($row['visit_id']); 
$title = htmlspecialchars($row['why_visit'); 

} 

} 

} 
+0

哦,我的上帝,我的眼睛! –

+0

**警告**您的代碼可能容易受到sql注入攻擊。 –

+0

如何添加一些別名,以縮小您的查詢? –

回答

2

按MySQL的文檔:http://dev.mysql.com/doc/refman/5.0/en/union.html

如果您要訂購的整個結果集,ORDER BY子句必須放在聯合中最後一個查詢,每個查詢中括號內。

(SELECT ...) 
UNION 
(SELECT ...) 
ORDER BY ... 
+0

謝謝馬克。我試過了,但它仍然顯示出相同的結果。 – ariel

+0

通過修復其他東西來實現它。現在工作良好。謝謝。 – ariel

0

......應該這樣做。

SELECT Tbl1.field1 
    FROM (SELECT field1 FROM table1 
      UNION 
      SELECT field1 FROM table2 
     ) Tbl1 
    ORDER BY Tbl1.field1