问题
I have a field containg a combined date, something line 2012-02-03 - 2012-02-05 where the first date is the "from" date, and second is the "to" date.
Is there a way that I can split these two dates and then order by the "from" date ?
I know the best thing would be to have two different fields for these two dates, but since I began doing it this way there is alot of recoding to seperate them.
回答1:
You can use SUBSTRING_INDEX for this.
Assuming your dates have ' - ' between them (i.e. space, hypen, space), you can do something like:
SELECT SUBSTRING_INDEX(datefield,' - ',1) as fromDate,
SUBSTRING_INDEX(datefield,' - ',-1) as toDate,
FROM ..
ORDER BY DATE(fromDate)
SUBSTRING_INDEX(string,delimiter,count)
returns all of string
up to (not including) the count
th occurence of delimiter
. If delimiter
is negative it counts from the right and returns the substring from the end of the string instead.
I used DATE(fromDate)
to convert fromDate
from a string to a MySQL Date so it sorts in a date-like fashion.
回答2:
or, if your dates have exactly 10 characters lenght, you can use SUBSTRING as follows http://sqlfiddle.com/#!2/53006/4
回答3:
You can you left and right function to get the 10 digit from left in that column and 10 digit from right in column, using alias from_date and to_date then order by.
2012-02-03 - 2012-02-05
__________ __________
Left 10 Right 10
Digits Digits
SELECT LEFT(mydate,10) AS from_date,
RIGHT(mydate,10) AS to_date
FROM mytable
ORDER BY from_date,to_date;
来源:https://stackoverflow.com/questions/9529198/splitting-fields-in-sql-query-and-sorting-by-them