How can i replace one row with 5 rows with same data in mysql.for example i have this table
id | companyId | name | open | close
1 | 1 | mon-fri | 10:00 | 19:00
2 | 1 | sat | 10:00 | 12:00
3 | 1 | sun | 10:00 | 12:00
4 | 2 | mon-fri | 10:00 | 16:00
5 | 2 | sat | 10:00 | 13:00
6 | 2 | sun | 10:00 | 13:00
I want to convert name field where its mon-fri to mon , tues , wed , thur , fri .
id | companyId | name | open | close
1 | 1 | mon | 10:00 | 19:00
2 | 1 | tues | 10:00 | 19:00
3 | 1 | wed | 10:00 | 19:00
4 | 1 | thur | 10:00 | 19:00
5 | 1 | fri | 10:00 | 19:00
6 | 1 | sat | 10:00 | 12:00
7 | 1 | sun | 10:00 | 12:00
.
.
.
You can’t do this via an
UPDATE, but what you can do is a series ofINSERT INTO ... SELECTmaking use of some string literals, followed by aDELETEto remove the rows you expanded out.http://sqlfiddle.com/#!2/cae33/1
(Credit where due: this excellent suggestion was the work of Andriy M in an unsolicited edit)
You could also reduce the number of statements, as well as the number of table scans, by using a virtual table, like this:
http://sqlfiddle.com/#!2/98e35/1
Update after comments:
There is no real value to forcing their order when you insert the rows, that is best done in
SELECT.To order by day for each
companyId, it will require some work no matter which way it is done. You could callLOWER(STR_TO_DATE())with%aand compare the weekday value, however you would also need to change yourthurtothusince that is how MySQL abbreviates it. That results in a bunch of function calls.Instead, you can use a
CASE....in theORDER BYto assign ordinal values to each day, like:Neither of the above methods is going to be friendly to indexing though.
If you need this to be more performant, I would recommend against storing the strings
'mon','tue','wed',etc in the first place, and instead storing their associated weekday value. SeeDAYOFWEEK()for details.