Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php selecting multiple rows from array of ids [duplicate]

Tags:

php

mysql

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!

like image 687
Steve Kim Avatar asked Nov 21 '25 09:11

Steve Kim


1 Answers

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 )";
like image 90
Aniket Sahrawat Avatar answered Nov 23 '25 23:11

Aniket Sahrawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!