我有一个关于SQL语法的问题,以及在单个查询中是否可以执行特定操作。请考虑以下示例:
假设我们有食谱表。每个食谱都有5种成分列在了成分1,成分2等栏目之下。让我们也说突然发现糖对你来说是不健康的,每个食谱必须在每个成分列中用“人造甜味剂”代替“糖”。我遇到的问题是没有成分表,因此每个成分都列在五列之一,而不是像成分ID那样引用。
如果可能,我该如何编写以下(伪)查询?
UPDATE Recipe
(SET ingredient1 = 'artificial sweetener' WHERE ingredient1 = 'sugar') OR
(SET ingredient2 = 'artificial sweetener' WHERE ingredient2 = 'sugar') OR
(SET ingredient3 = 'artificial sweetener' WHERE ingredient3 = 'sugar') OR
(SET ingredient4 = 'artificial sweetener' WHERE ingredient4 = 'sugar') OR
(SET ingredient5 = 'artificial sweetener' WHERE ingredient5 = 'sugar')
我在网上发现了多篇关于根据列当前值将列设置为某个值的文章,但不仅限于设置包含值的特定列。非常感谢任何帮助。
答案 0 :(得分:5)
我会用“你不想听到的”答案回答你的问题。您错误地设计了数据库。
你应该有结构:
Recipe
RecipeID, other recipe information
Ingredient
IngredientID, RecipeID, Ingredient, Measurement...
理想情况下,实际上,您可能会将Ingredient
作为查找表,并将RecipeIngredient
作为包含测量信息和IngredientID
的联接表,但上述内容仍然会很明显比你拥有的更好。
然后你的更新将是:
update Ingredient
set Ingredient='artificial sweetener'
where Ingredient='sugar'
答案 1 :(得分:4)
CASE表达式将指示是否需要修改五列中的每一列。使用WHERE子句筛选出不需要修改的任何行:
UPDATE Recipe
SET ingredient1 = CASE WHEN ( ingredient1 = 'sugar' )
THEN 'artificial sweetener' ELSE ingredient1 END ,
SET ingredient2 = CASE WHEN ( ingredient2 = 'sugar' )
THEN 'artificial sweetener' ELSE ingredient2 END ,
SET ingredient3 = CASE WHEN ( ingredient3 = 'sugar' )
THEN 'artificial sweetener' ELSE ingredient3 END ,
SET ingredient4 = CASE WHEN ( ingredient4 = 'sugar' )
THEN 'artificial sweetener' ELSE ingredient4 END ,
SET ingredient5 = CASE WHEN ( ingredient5 = 'sugar' )
THEN 'artificial sweetener' ELSE ingredient5 END
WHERE 'sugar' IN
( ingredient1, ingredient2, ingredient3, ingredient4, ingredient5 )
;
答案 2 :(得分:1)
考虑到重新设计数据库,您当前的设计不是很友好.. 无论如何,你要找的答案是使用case-when update子句;
UPDATE tablename
SET
INGREDIENT1 = CASE WHEN INGREDIENT1='SUGAR' THEN 'ARTIFICIAL SWEETENER' ELSE INGREDIENT1 END,
INGREDIENT2 = CASE WHEN INGREDIENT2='SUGAR' THEN 'ARTIFICIAL SWEETENER' ELSE INGREDIENT2 END
答案 3 :(得分:0)
您可以执行以下操作:
UPDATE Recipe SET
ingredient1 = if(ingredient1 = 'sugar', 'artificial sweetener', ingredient1),
ingredient2 = if(ingredient2 = 'sugar', 'artificial sweetener', ingredient2),
..etc..
答案 4 :(得分:0)
以下内容有点便携:
UPDATE Recipe
SET ingredient1 = CASE ingredient1 WHEN 'sugar' THEN 'artificial sweetener' ELSE ingredient1 END,
SET ingredient2 = CASE ingredient2 WHEN 'sugar' THEN 'artificial sweetener' ELSE ingredient2 END,
SET ingredient3 = CASE ingredient3 WHEN 'sugar' THEN 'artificial sweetener' ELSE ingredient3 END,
SET ingredient4 = CASE ingredient4 WHEN 'sugar' THEN 'artificial sweetener' ELSE ingredient4 END,
SET ingredient5 = CASE ingredient5 WHEN 'sugar' THEN 'artificial sweetener' ELSE ingredient5 END
WHERE ingredient1 = 'sugar'
OR ingredient2 = 'sugar'
OR ingredient3 = 'sugar'
OR ingredient4 = 'sugar'
OR ingredient5 = 'sugar'
请注意,只要配方中有任何糖,无论当前值如何,这都会在技术上更新所有这些列。这是使用单个UPDATE
语句和此模式的结果。查询优化器通常根据整行和列来考虑,而不是单个值。