2016-04-10 3 views
1

私は、異なるテーブルの3つの別々のクエリの結果を各テーブルのタイムスタンプフィールドでソートする方法を探しています。PHPのタイムスタンプフィールドで複数のsqlクエリをアレンジするアルゴリズム

$sql1 = "SELECT * FROM chores WHERE Status = 'unchecked' ORDER BY Time DESC"; 
$sql2 = "SELECT * FROM contacts WHERE Status = 'unchecked' ORDER BY DateTime DESC"; 
$sql3 = "SELECT * FROM gyms WHERE Status = 'unchecked' WHERE Endtime IS NOT 
NULL ORDER BY EndTime DESC"; 

は、だから私は、これらの3つのクエリを持っていると言う、と私は、タイムスタンプフィールド、他のテーブルのすべての他のすべての行に比べて、第三最古のある行のデータが欲しいです。 SQLクエリやPHPでこれを行う簡単な方法はありますか?私はそれのための論理を理解することに苦労している。

+0

...あなたはあなたのクエリを実行していることを前提とし、すべての行を含む3つの別々の連想配列を持っていますが、これらの場合スキームが異なる場合は、このレコードをPHPコード –

+2

にソートしてください。データと期待される結果のサンプルを書いてください。 –

+0

はい、それぞれ異なる計画です。同じ唯一のものはタイムスタンプです。 – user1760150

答えて

1

あなたは `UNION`を使用することができます同じスキームで、この3つのテーブル場合

$array1, $array2, and $array3 

$test = array_merge($array1, $array2, $array3); 
usort($test, 'sortit'); 
print_r($test); 

function sortit($a, $b){ 
    /* 
     Note, if the column name for the timestamp is not the same for each table, 
     this function must know what element to compare for a proper sort. 

     Also, this is assuming that the [timestamp] field is a linux epoch, if it is not, then 
     simply do this: 

     $a_time = strtotime($a['DateString']); 
     $b_time = strtotime($b['TimeString']); 
     return $a_time >= $b_time ? 1 : -1; 
    */ 
    return $a['timestamp'] >= $b['timestamp'] ? 1 : -1; 
} 
関連する問題