你不能通过 a 来做到这一点UPDATE
,但你可以做的是一系列INSERT INTO ... SELECT
使用一些字符串文字,然后是 aDELETE
来删除你展开的行。
/* First insert a row for each mon,tue,wed,thur,fri */
/* Column values are copied from the existing mon-fri row, and use the literal strings 'mon', 'tue', etc as the new `name` */
INSERT INTO yourtable (`companyId`, `name`, `open`, `close`)
SELECT `companyId`, 'mon', `open`, `close` FROM yourtable WHERE `name` = 'mon-fri'
INSERT INTO yourtable (`companyId`, `name`, `open`, `close`)
SELECT `companyId`, 'tue', `open`, `close` FROM yourtable WHERE `name` = 'mon-fri'
INSERT INTO yourtable (`companyId`, `name`, `open`, `close`)
SELECT `companyId`, 'wed', `open`, `close` FROM yourtable WHERE `name` = 'mon-fri'
INSERT INTO yourtable (`companyId`, `name`, `open`, `close`)
SELECT `companyId`, 'thur', `open`, `close` FROM yourtable WHERE `name` = 'mon-fri'
INSERT INTO yourtable (`companyId`, `name`, `open`, `close`)
SELECT `companyId`, 'fri', `open`, `close` FROM yourtable WHERE `name` = 'mon-fri'
/* Then delete the original mon-fri rows which you just expanded out */
DELETE FROM yourtable WHERE `name` = 'mon-fri'
http://sqlfiddle.com/#!2/cae33/1
(归功于:这个出色的建议是Andriy M在未经请求的编辑中的作品)
您还可以通过使用虚拟表来减少语句的数量以及表扫描的数量,如下所示:
/* Cross-join the existing 'mon-fri' rows with a virtual table of day names
of 'mon' through 'fri' and insert the resulting set back into your table */
INSERT INTO yourtable (`companyId`, `name`, `open`, `close`)
SELECT t.`companyId`, v.`name`, t.`open`, t.`close`
FROM yourtable t
CROSS JOIN (
SELECT 'mon' AS `name` UNION ALL
SELECT 'tue' UNION ALL
SELECT 'wed' UNION ALL
SELECT 'thur' UNION ALL
SELECT 'fri'
) v
WHERE t.`name` = 'mon-fri';
/* Then delete the original mon-fri rows which you just expanded out */
DELETE FROM yourtable WHERE `name` = 'mon-fri';
http://sqlfiddle.com/#!2/98e35/1
评论后更新:
插入行时强制它们的顺序没有真正的价值,最好在SELECT
.
要按天订购,companyId
无论采用哪种方式,都需要做一些工作。您可以调用LOWER(STR_TO_DATE())
并%a
比较工作日值,但是您还需要更改您的thur
to,thu
因为这是 MySQL 的缩写方式。这会导致一堆函数调用。
相反,您可以使用 aCASE....
来ORDER BY
为每一天分配序数值,例如:
ORDER BY
companyId,
CASE `name`
WHEN 'sun' THEN 1
WHEN 'mon' THEN 2
WHEN 'tue' THEN 3
WHEN 'wed' THEN 4
WHEN 'thur' THEN 5
WHEN 'fri' THEN 6
WHEN 'sat' THEN 7
ELSE 8 END
不过,上述两种方法都不会对索引友好。
如果您需要提高性能,我建议您'mon','tue','wed'
首先不要存储字符串等,而是存储它们关联的工作日值。详情请参阅DAYOFWEEK()
。