I have a table which stores 0-6 as weekday value, and I want to display weekday name. Eg if value is 0
, it will display Sunday
, if value is 1
, it will display Monday
, likewise. Is there any inbuilt MySQL function for getting day name from Index?
Thanks in Advance!!
As @Aliminator mentioned, you could use DAYNAME
with a DATE
.
However, if you don't want to change your schema, here is a nifty hack for you:
SELECT DAYNAME(CONCAT("1970-09-2", dayIndex)) FROM your_table;
This is based on the fact that 1970-09-20 was a Sunday, the 21st was a Monday, and so on.
DAYNAME( date_value )
is available in MySql; however, this takes a date, not an int. So if you have the date available, you can just use DAYNAME(CURDATE())
, DAYNAME('2014-01-07')
, etc.
If all you have available is the int representing the weekday, then a CASE statement might be your best bet.
CASE WHEN 0 THEN 'Sunday' WHEN 1 THEN 'Monday' ..... ELSE '' END
Method 1:
Use a CASE
expression.
Query
select *,
case when weekid = 0 then 'Sunday'
when weekid = 1 then 'Monday'
when weekid = 2 then 'Tuesday'
when weekid = 3 then 'Wednesday'
when weekid = 4 then 'Thursday'
when weekid = 5 then 'Friday'
when weekid = 6 then 'Saturday'
else null end as WeekName
from your_table;
Method 2:
You can create a table for storing the week names and select it using JOIN
.
Table weekName
create table tblWeekName
(
id int,
weekName varchar(20)
);
insert into tblWeekName values
(0,'Sunday'),(1,'Monday'),(2,'Tuesday'),
(3,'Wednesday'),(4,'Thursday'),(5,'Friday'),(6,'Saturday');
Then use the following query to select the weekname.
select t1.*,
t2.weekName
from your_table t1
join tblWeekName t2
on t1.weekid = t2.id;
There is a reduced variant of previous answers - you can write one time your name of column in CASE statement to reduce length of your code.
case tt.start_day_of_week
when 0 then 'Sunday'
when 1 then 'Monday'
when 2 then 'Tuesday'
when 3 then 'Wednesday'
when 4 then 'Thursday'
when 5 then 'Friday'
when 6 then 'Saturday'
else null end
I looked through the MySql 5.5 documentation and there is a function when selecting called DayName() that you may be able to use. The down side is that you will need to use a DateTime variable, not an int.
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayname
I suggest changing your schema to take a DateTime so you can use DayName() and other built-in functions.
Are you sure that you really need to store the name of the weekday? If you need to get the week day for the stored date try DATE_FORMAT(date,format)
with '%W'
or '%w'
format parameter. See here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.