如何使用Order BY正确使用Union?

时间:2012-05-05 01:21:45

标签: php mysql sql-order-by union

我下面的代码加入了5个表,然后假设按date_timed_added排序。如果我只加入4个表,那么查询工作得很好。出于某种原因,在第4桌之后,它给了我一些问题。问题在于它先排序并显示第5个表,然后是其余的表。我如何修复它,以便通过查询所有其他表来正确排序date_time_added?

//$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');

 }

 }

 }

2 个答案:

答案 0 :(得分:2)

根据MySQL文档:http://dev.mysql.com/doc/refman/5.0/en/union.html

如果要订购ENTIRE结果集,则必须将ORDER BY子句置于UNION中的LAST查询中,并将每个查询置于括号内。

(SELECT ...)
UNION
(SELECT ...)
ORDER BY ...

答案 1 :(得分:0)

这样做应该这样做。

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