php_guest Posted February 6, 2009 Share Posted February 6, 2009 I have two tables: table One: UserID | mainTitle | time table Two: ID | xTitle | time Time is in datetime format. I would like to select rows mainTitles and time from table one and rows xTitles and time from table two. Then I would like to order all results by time. I tried the following code, but it doesn't work: $result = mysql_query("('SELECT * FROM One WHERE UserID=$ID') UNION ('SELECT * FROM Two WHERE ID=$ID') ORDER BY time"); while($row = mysql_fetch_assoc($result)) { ... } Please help me how to print fields from mainTitle and xTitle in the way to be ordered by time. Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/144123-displaying-from-2-tables-and-order-by-1-row/ Share on other sites More sharing options...
php_guest Posted February 6, 2009 Author Share Posted February 6, 2009 I did some correction inside the first line, but still doesn't work. $result = mysql_query("(SELECT * FROM One WHERE UserID='$ID') UNION ('SELECT * FROM Two WHERE ID='$ID')) ORDER BY time"); while($row = mysql_fetch_assoc($result)) { ... } Quote Link to comment https://forums.phpfreaks.com/topic/144123-displaying-from-2-tables-and-order-by-1-row/#findComment-756287 Share on other sites More sharing options...
anthylon Posted February 8, 2009 Share Posted February 8, 2009 Hello, I am confused about field type: UserID. Is it numeric? If yes you need to remove apostrophe ' from your query. Also you have one extra apostrophe before second select UNION ('SELECT... Remove it as well. Please not one extra closed bracket in second select statement ... WHERE ID='$ID')) Your query should be like this: $result = mysql_query("(SELECT * FROM One WHERE UserID=$ID) UNION (SELECT * FROM Two WHERE ID=$ID)) ORDER BY time"); Don't forget union method request the same number of fields in both tables. :-\ Cheers Quote Link to comment https://forums.phpfreaks.com/topic/144123-displaying-from-2-tables-and-order-by-1-row/#findComment-757254 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.