Frage

I'm trying convert a date that is stored in a mysql datebase as a VARCHAR (format example: 12/29/2012) and then I want to ORDER BY it so that the older dates are on top followed by fore current dates.

Eg: 
11-01-2012
11-05-2012
12-25-2012
...

Here is what I have so far, (PLEASE HELP!! THANKS)

<?php
        $listsql = "SELECT contact.id, CONCAT(lastname,', ',firstname) AS fullname, lastname, firstname,
                    STR_TO_DATE(daDATE,'%m-%d-%Y'), line1, line2, city, state, zip, phone1, phone2, country, whoAdded
                    FROM ". TABLE_CONTACT ." AS contact
                    LEFT JOIN ". TABLE_ADDRESS. " AS address ON contact.id=address.id AND contact.primaryAddType=address.type
                    LEFT JOIN ". TABLE_EMAIL ." AS email ON contact.id=email.id AND contact.primaryAddType=email.type
                    WHERE contact.hidden != 1
                    ORDER BY email.daDATE";
?>
War es hilfreich?

Lösung

As the comments have indicated to you. You REALLY should change the field type to a date or datetime (if you need H-M-S info). While you can certainly do string manipulation on a date value in a text type field, you will not have any way to use an index to make filtering/sorting/grouping that you may want to do on that field efficient.

If you need help converting I might suggest this approach. Add a new date or datetime column. Make sure to add an index on this column since you will be using it for ordering.

Then run this query:

UPDATE table SET new_date_column = STR_TO_DATE(old_date_column, '%m-%d-%Y');

Then delete the old column from the table.

Andere Tipps

you can order it on the fly using SUBSTR() and INSTR() to identify each part of the date, then order by the year, then month then day part. Like everyone else said, it is better to either store it as a date or unixtime integer. You can change it to yyyy-mm-dd and the orderby would work natively.

if you insist on the most difficult way possible it would be something like (year, month, day):

ORDER BY SUBSTR(email.daDATE,INSTR(email.daDATE,'-',2)+1) DESC,
         SUBSTR(email.daDATE,INSTR(email.daDATE,'-',1)+1,INSTR(email.daDATE,'-',2)-1) DESC,
         SUBSTR(email.daDATE,0,INSTR(email.daDATE,'-')-1) DESC

or something like that. this was on the fly off the top of my head, but I think it is accurate. Look up the functions for their usage if it doesnt work as intended.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top