php - How to order rows by a field that exists on both table while using JOIN statement -
main table: 'posts'.
structure:
id || text || time || user_id
secondary table: 'likes'.
structure:
id || post_id || time || user_id
here, post_id 2nd table can (& must) id 1st table. running query fetch ids posts table of specific user_id , post_ids likes table of specific user_id. query:
select p.id posts p left join likes l on p.id=l.post_id p.user_id=$userid or l.user_id=$userid
the time field on both table numeric, type int (12). unix timestamp stored in here, 1234567890. order data i'm fetching time field on both table.
for example, there 2 posts in posts table, post id 1 has time value of 1234567891, post id 2 has time value of 1234567896. , there's 1 post id 3 in likes table time value of 1234567893.
i order rows time, this:
post id 1, post id 3, post id 2.
as post id 3 occured before post id 2. how go since time , it's value can in either tables.
thanks!
after join have 2 time columns, 1 each table. need give sql logic use order both - example, ordering max(l.time,p.time) whichever greater.
basically, when "i order data i'm fetching time field on both table", need define more clearly, , should straightforward want. try thinking how hand, or how instruct hand - if handed them these records on pieces of paper , said "put these in order time fields in both sets of data", wouldn't know - , neither mysql!
Comments
Post a Comment