我真的希望你能帮我解决这个问题。我试图根据旧字段长度是否大于1来运行两种不同类型的更新查询。这背后的想法是,当用户更新产品时,它会将ProductRef附加到Search表中,该表仅用于搜索。
如此简单,如果ProductRef的字符串长度大于0,请将旧产品ref替换为新产品。否则,添加新产品参考。这是我到目前为止,但它似乎触发了一个错误 -
-- Update the ProductType UpdatedTS that corresponds with this product
-- The below section simply updates the main products UpdatedTS
UPDATE tbl_product_types
SET UpdatedTS = now()
WHERE ID = New.ProductTypeID;
IF ( SELECT Length(Old.ProductRef) > 0 )
BEGIN
-- We have already stored the product reference so run a replace
UPDATE tbl_product_type_search AS STable
SET `STable.Search` = replace(`Search`,CONCAT(Old.ProductRef,' '),New.ProductRef)
WHERE `STable.ProductTypeID` = Old.ProductTypeID
END
ELSE
BEGIN
-- We haven't yet stored the product reference, store it
UPDATE tbl_product_type_search AS STable
SET `STable.Search` = CONCAT(NEW.ProductRef,' ',`STable.Search`)
WHERE STable.ProductTypeID = New.ProductTypeID
END
供您参考,以下是相关的DB结构:
答案 0 :(得分:1)
似乎是UPDATE触发器。不是吗?如果是这样,请尝试此代码(有一些语法错误) -
UPDATE
tbl_product_types
SET
UpdatedTS = NOW()
WHERE ID = NEW.ProductTypeID;
IF (SELECT length(Old.ProductRef) > 0) THEN
-- We have already stored the product reference so run a replace
UPDATE
tbl_product_type_search AS STable
SET
`STable.Search` = REPLACE(`Search`, CONCAT(Old.ProductRef, ' '), NEW.ProductRef)
WHERE
`STable.ProductTypeID` = OLD.ProductTypeID;
ELSE
-- We haven't yet stored the product reference, store it
UPDATE
tbl_product_type_search AS STable
SET
`STable.Search` = CONCAT(NEW.ProductRef, ' ', `STable.Search`)
WHERE
STable.ProductTypeID = NEW.ProductTypeID;
END IF;
将两个UPDATE语句合并为一个:
UPDATE
tbl_product_type_search AS STable
SET
`STable.Search` =
IF(
LENGTH(OLD.ProductRef) > 0,
REPLACE(`Search`, CONCAT(OLD.ProductRef,' '), NEW.ProductRef),
CONCAT(NEW.ProductRef, ' ', `STable.Search`)
)
WHERE
LENGTH(OLD.ProductRef) > 0 AND `STable.ProductTypeID` = OLD.ProductTypeID
OR
LENGTH(OLD.ProductRef) <= 0 AND STable.ProductTypeID = NEW.ProductTypeID
关于分隔符:
DELIMITER $$
CREATE TRIGGER trigger_name
AFTER UPDATE
ON table_name
FOR EACH ROW
BEGIN
UPDATE tbl_product_types...;
other statements...;
END
$$
DELIMITER ;
答案 1 :(得分:0)
以下是未经测试的更新if语句。你可以尝试一下。
UPDATE tbl_product_type_search AS STable
inner join tbl_product_type_search as Old on STable.ID=Old.ID
SET `STable.Search` =
IF(Length(Old.ProductRef) > 0 AND `STable.ProductTypeID` = Old.ProductTypeID,
replace(`Search`,CONCAT(Old.ProductRef,' '),New.ProductRef),
IF(Length(Old.ProductRef) < 0 AND STable.ProductTypeID = New.ProductTypeID,
CONCAT(NEW.ProductRef,' ',`STable.Search`) ,`STable.Search` ));