Forum Moderators: open

Message Too Old, No Replies

Order By Date Issue with Union

         

HoboTraveler

7:21 pm on Aug 9, 2006 (gmt 0)

10+ Year Member



Hello,

I have two tables from which I am generating a table with the results. I am using the UNION parameter to combine the two MySQL SELECT statements and ORDER BY to ensure that the results are ordered by the Datetime field.

The issue that I am faced with is that, the results are not being ORDERED correctly by date. Many of the newest results from the second table are found towards the end of the results. I tried the BINARY ORDER BY and the results worsened..

Is there a way to fix this issue? And have the results from both tables ORDERED by date?

MySQL version: 4.1.20
Table Type: MyISAM
Date_format field Type: datetime [the field is update through NOW()]

Code Snippet:

SELECT

tab1-ID,
date_format(tab1-date, '%M %D %W, %Y %l:%i %p') AS tab1-date,
tab1-email

FROM
table1
WHERE
tab1-email = 'test@foo.com'

UNION

SELECT
tab2-ID,
date_format(tab2-date, '%M %D %W, %Y %l:%i %p') AS tab2-date,
tab2-email
FROM
table2
WHERE
tab2-email = 'test@foo.com'
ORDER BY
2 DESC

-- End--

TIA

[edited by: HoboTraveler at 7:24 pm (utc) on Aug. 9, 2006]

LifeinAsia

8:42 pm on Aug 9, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Um, since tab2-date is displaying (in order) month, day, week(?), year, etc., and being converted into a text string, I can imagine you're not getting the results you're expecting!

Example:
January 1, 2002 would be "1 1 1 2002" and
January 3, 2001 would be "1 3 1 2001" so of course "1 1 1 2002" (January 1, 2002) will come before "1 3 1 2001" (January 3, 2001) in character sort order.

Either change the order of your text conversion to year, month, day or sort on the original datetime field (not the converted string output).

This shows why it is bad practice to use alias names that are identical to existing field names.

HoboTraveler

5:12 am on Aug 10, 2006 (gmt 0)

10+ Year Member



Thank-You.. I am Ordering by the original datetime field now..

Works Perfect.

Thanks..