2016-11-10 52 views
3

對於mysql表,我有10行和5(一半)有post_id5,而其他5行有post_id234php從ID數組中選擇多行

我想從基於日期每POST_ID選擇2行:

這是我迄今爲止

$post_ids = $_POST['id'][0]; 
$ids  = implode(',', $post_ids); //id's in ',' format 

$query = "SELECT * FROM $table WHERE post_id in ({$ids}) ORDER by date desc limit 2"; 

這隻能獲取匹配兩個ID中的一個頭兩個結果。我需要爲每個查詢運行foreach函數嗎?有另一種方法嗎?

謝謝!

+1

是放在foreach循環查詢其獲取DB的所有記錄,然後把查詢內環路 –

+0

感謝您的幫助。看起來這是最簡單的方法。謝謝! –

+0

沒有正確理解,但你有沒有考慮[GROUP BY](https://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html) – bansi

回答

3

您可以使用UNION ALL執行此任務。試試這個:

$query = "(select * from $table where post_id = $ids[0] order by date desc LIMIT 1) UNION ALL (select * from $table where post_id = $ids[1] order by age desc LIMIT 1)";