For mysql table, I have 10 rows and 5 (half) of them have post_id of 5 while the other 5 rows have post_id of 234.
I want to choose 2 rows from each post_id based on the date:
This is what I have so far
$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";
This only gets first two results that matches one of two ids. Do I need to run foreach function for the each query? Is there another method?
Thanks!
You can use UNION ALL for this task. Try this:
$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 )";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With