DB有几个表,tblPizza,然后是其配料表,tblCheese,tblMeat和tblVeggie。我想编写一个MySQL函数,它将使用VARCHAR参数,在每个表中查找priceFactor,将它们加在一起,然后返回该小数。谷歌搜索和搜索后,我拼凑了这个。我在这里或谷歌上找到的结果都没有试图与我想做的事情做得足够接近。
DELIMITER $$
CREATE FUNCTION `dbname`.`calculatePrice` (cheese VARCHAR(50), meat VARCHAR(50), veg VARCHAR(50))
RETURNS DECIMAL
BEGIN
DECLARE price DECIMAL;
SET price = SUM(SELECT priceFactor AS cheesePrice UNION ALL SELECT priceFactor AS meatPrice FROM tblMeat WHERE meatName = meat UNION ALL SELECT priceFactor AS vegPrice FROM tblVeggie WHERE veggieName = veg) FROM tblCheese WHERE cheeseName = cheese);
RETURN price;
END
MySQL不喜欢SUM之后的SELECT,但我不知道如何在没有子查询的情况下得到我想要的东西。每个表中都有重复的列名,并且表之间没有相关性来证明JOIN的合理性。
结果将被踢回PHP,这将JSON与jQuery一起。
谢谢! 99%的时间,我可以在这里找到我需要的^ _ ^
编辑注意,一个(但只有一个)参数可能为空。用户只需要选择两个披萨配料,但不能选择不到这个。
答案 0 :(得分:1)
试试这个,
SET price =
(
SELECT SUM(x.Price)
FROM
(
SELECT priceFactor AS Price FROM tblCheese WHERE cheeseName = cheese
UNION ALL
SELECT priceFactor AS Price FROM tblMeat WHERE meatName = meat
UNION ALL
SELECT priceFactor AS Price FROM tblVeggie WHERE veggieName = veg
) x
);