Jump to content

Selecting latest record and union all


xoshbin

Recommended Posts

hi im new here and i hope being helpfull and help me too.i have this code i want to select latest records from three tables (order by id) it works fine but its adds records of latest table on the bottom and the second one betwen first table and third table. what i want is when i add a record for the third one goes to top not in the botom here's the code:

$result = mysql_query('(SELECT colum1, colum2 FROM tbl1 ORDER BY id DESC LIMIT 2) UNION ALL(SELECT colum1, colum2 FROM tbl2 ORDER BY id DESC LIMIT 1) UNION ALL(SELECT colum1, colum2 FROM tbl3 ORDER BY id DESC LIMIT 1)');while($row = mysql_fetch_array($result)){}

Link to comment
Share on other sites

Thanks for your repliehere its what i did if you mean that but still not working

$result = mysql_query('(SELECT colum1, colum2 FROM tbl1) UNION ALL(SELECT colum1, colum2 FROM tbl2) UNION ALL(SELECT colum1, colum2 FROM tbl3) ORDER BY id DESC LIMIT 4');

Thanks for your time

Link to comment
Share on other sites

You may need to add the id to the list of columns to select if you're going to be ordering by that. I'm not sure how you want it to work, but you may also want to put the LIMIT statements back with each table (as it is now, it gets the 4 most recent regardless of which table they come from). Other than that, if it's not working let me know what it is or is not doing that's wrong.

Link to comment
Share on other sites

All of the tables has id columns. i want to select 4 records from these tables order by latest one added, and the tables has date column i have tried to order lts records by date but still not works here is how for the date

$result = mysql_query('(SELECT colum1, colum2 FROM tbl1 ORDER BY date DESC LIMIT 2) UNION ALL(SELECT colum1, colum2 FROM tbl2 ORDER BY date DESC LIMIT 1) UNION ALL(SELECT colum1, colum2 FROM tbl3 ORDER BY date DESC LIMIT 1)');

Link to comment
Share on other sites

I'm saying try something like this:$result = mysql_query('(SELECT id, colum1, colum2 FROM tbl1) UNION ALL(SELECT id, colum1, colum2 FROM tbl2) UNION ALL(SELECT id, colum1, colum2 FROM tbl3) ORDER BY id DESC LIMIT 4');Notice the IDs are in the select list. If that doesn't work, tell me what "doesn't work" means.

Link to comment
Share on other sites

Ok thanks thats great worked :) But i tried this to select latest record by date but didnt work

$result = mysql_query('(SELECT date, colum1, colum2 FROM tbl1) UNION ALL(SELECT date, colum1, colum2 FROM tbl2) UNION ALL(SELECT date, colum1, colum2 FROM tbl3) ORDER BY date DESC LIMIT 4');

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...