Mysql:用什么代替 WITH 语句或 TEMPORARY 表?
Mysql: what to use instead of WITH statement or TEMPORARY tables?
有没有办法将 select 查询存储到 table 中?我通常使用 WITH 语句
但这只有 mysql 8+ 才有可能。我目前正在使用 mysql 5.1。因此,我尝试实现一个临时 table 但不可能在同一查询中多次引用临时 table(如下面的查询)。
CREATE TEMPORARY TABLE test
SELECT TIMESTAMPDIFF(MONTH, MAX(L.period), CURDATE()) as timediff, L.contractID
FROM license L GROUP BY L.contractID;
UPDATE `contract` AS C
SET C.valid = CASE
WHEN (SELECT timediff FROM test AS T WHERE T.contractID = C.contractID) < 1 THEN 2
WHEN (SELECT timediff FROM test AS T WHERE T.contractID = C.contractID) = 1 THEN 1
WHEN (SELECT timediff FROM test AS T WHERE T.contractID = C.contractID) > 1 THEN 0
END;
DROP TEMPORARY TABLE test;
您可以通过将更新表述为连接来立即解决您的问题:
UPDATE contract c
INNER JOIN test t
ON t.contractID = c.contractID
SET valid = CASE WHEN t.timediff < 1 THEN 2
WHEN t.timediff = 1 THEN 1
ELSE 0 END;
这种方法解决了多次引用临时 table 的问题。
有没有办法将 select 查询存储到 table 中?我通常使用 WITH 语句 但这只有 mysql 8+ 才有可能。我目前正在使用 mysql 5.1。因此,我尝试实现一个临时 table 但不可能在同一查询中多次引用临时 table(如下面的查询)。
CREATE TEMPORARY TABLE test
SELECT TIMESTAMPDIFF(MONTH, MAX(L.period), CURDATE()) as timediff, L.contractID
FROM license L GROUP BY L.contractID;
UPDATE `contract` AS C
SET C.valid = CASE
WHEN (SELECT timediff FROM test AS T WHERE T.contractID = C.contractID) < 1 THEN 2
WHEN (SELECT timediff FROM test AS T WHERE T.contractID = C.contractID) = 1 THEN 1
WHEN (SELECT timediff FROM test AS T WHERE T.contractID = C.contractID) > 1 THEN 0
END;
DROP TEMPORARY TABLE test;
您可以通过将更新表述为连接来立即解决您的问题:
UPDATE contract c
INNER JOIN test t
ON t.contractID = c.contractID
SET valid = CASE WHEN t.timediff < 1 THEN 2
WHEN t.timediff = 1 THEN 1
ELSE 0 END;
这种方法解决了多次引用临时 table 的问题。