0

I have 3 mysql tables as below. tbl_objects, tbl_object_relationships and tbl_post. I want to get only the last 2 posts from each object by date.

Table 1) tbl_Objects
+-------------+---------------+
|  object_id  |  object_name  |
+-------------+---------------+
|      1      |      cars     |
|      2      |  motorcycles  |
+-------------+---------------+



Table 2) tbl_object_relationships
+-------------+---------------+
|  object_id  |  post_id  |
+-------------+------------+
|      1      |      3     |
|      1      |      5     |
|      1      |      7     |
|      2      |      4     |
|      2      |      2     |
|      1      |      1     |
|      2      |      6     |
|      2      |      8     |
+-------------+------------+



Table 3) tbl_posts
+------+------------+----------+
|  ID  |    name    |   date   |
+------+------------+----------+
|  1   |   toyota   |   2010   |
|  2   |   yamaha   |   2010   |
|  3   |   santafe  |   2014   |
|  4   |   suzuki   |   2011   |
|  5   |   bmw      |   2015   |
|  6   |   honda    |   2012   |
|  7   |   audi     |   2016   |
|  8   |   ducati   |   2013   |
+------+------------+----------+

I want results as array. Here is my desired array:

$result = array(
'cars' => array(
0 => array(
'ID' => '5',
'name' => 'bmw',
'date' => '2015'),
1 => array(
'ID' => '7',
'name' => 'audi',
'date' => '2016')
),    
'motocycles' => array(
0 => array(
'ID' => '6',
'name' => 'honda',
'date' => '2012'),
1 => array(
'ID' => '8',
'name' => 'ducati',
'date' => '2013')
)
);

Thanks for your answer.

  • try this [How to SELECT the newest four items per category](http://stackoverflow.com/a/1442867/4630403) – Frogger Jan 04 '17 at 09:43
  • so as per the above table you want to fetch the followings: `7 | audi | 2016 8 | ducati | 2013` as above is the last inserted record. – Randheer Singh Chouhan Jan 04 '17 at 10:06
  • 2
    Possible duplicate of [How to SELECT the newest four items per category?](http://stackoverflow.com/questions/1442527/how-to-select-the-newest-four-items-per-category) – CLAbeel Jan 04 '17 at 11:39

0 Answers0