获取上次查询的最后计数结果

时间:2014-06-02 08:43:23

标签: mysql sql

我想在if和else语句中使用this的输出,我该怎么做?

我已尝试直接将选择查询添加为此IF(选择查询)> 0那么,但它不起作用。我怎样才能实现这一目标?

SELECT COUNT(*) FROM service, kit, kit_has_part, part 
WHERE service.id = 1 and service.kitID = kit.id 
and kit.id = kit_has_part.kitID 
and kit_has_part.partID = part.id 
and part.stock > 0

1 个答案:

答案 0 :(得分:0)

一种简单的方法是声明一个变量并在其中选择结果。然后,您可以在IF中使用该变量。类似于伪代码的东西;

CREATE FUNCTION bop() RETURNS INT DETERMINISTIC
BEGIN
  DECLARE cnt INT;

  SELECT COUNT(*) INTO cnt
  FROM service
  JOIN kit ON kit.id = service.kitid
  JOIN kit_has_part ON kit_has_part.kitid = kit.id
  JOIN part ON part.id =  kit_has_part.partid
  WHERE service.id = 1 AND part.stock > 0;

  IF cnt > 0 THEN
    RETURN 1;
  ELSE
    RETURN 0;
  END IF;
END;
//