2012-05-05 11 views
0

以下のコードは5つのテーブルを結合し、date_timed_addedでソートすることを想定しています。私は4つのテーブルだけを結合する場合、クエリは完璧に働いた。何らかの理由で4番目のテーブルの後に、それは私に問題を与えます。問題は、最初に5番目のテーブルをソートして表示し、残りのテーブルを次に表示することです。どうすればそれを修正して、date_time_addedを適切に並べ替えることができますか?Unionを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

Ohh私の神、私の目! –

+0

**警告**あなたのコードはおそらくSQLインジェクション攻撃の脆弱性があります。 –

+0

いくつかのエイリアスを追加してクエリを小さくするのはどうですか? –

答えて

2

http://dev.mysql.com/doc/refman/5.0/en/union.html

あなたは結果セット全体を注文したい場合は、ORDER BY句は、各クエリが括弧された状態で、UNIONの最後の問合せに配置する必要があります。

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

ありがとうございました。私はそれを試みたが、それは私に同じ結果をまだ示す。 – ariel

+0

他のものを修正することで動作するようになりました。今はうまく動作します。ありがとう。 – ariel

0

sthこのようにする必要があります。

MySQLのドキュメントを1として
SELECT Tbl1.field1 
    FROM (SELECT field1 FROM table1 
      UNION 
      SELECT field1 FROM table2 
     ) Tbl1 
    ORDER BY Tbl1.field1 
関連する問題