MySQL案例基于查询返回的结果执行查询

时间:2015-03-25 20:59:05

标签: mysql

我想要达到的目标是, 如果查询返回的行数:

SELECT count(*) FROM `games` WHERE cateID=2 AND active=1

是EQUAL为0,我想运行一个插入查询:

INSERT INTO games(cateID ,time,users,active)
                VALUES ('2', '1', '0', '1')

我尝试使用这样的案例:

SELECT CASE WHEN SELECT count(*) FROM `games` WHERE cateID=2 AND active=1)=0
    THEN INSERT INTO games(cateID ,time,users,active)
                VALUES ('2', '1', '0', '1')
END

但它返回错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT count(*) FROM `games` WHERE cateID=2 AND active=1)=0
    THEN INSERT INTO' at line 1 

注意:两个查询单独执行时,执行时没有任何错误。 我如何实现这一目标?

修改

还尝试使用IF,

SELECT if(count(*)==0,INSERT INTO games(cateID ,time,users,active)
                VALUES ('2', '1', '0', '1')) FROM `games` WHERE cateID=2 AND active=1

仍然会出现同样的错误。 编辑2: 根据建议的评论,

INSERT INTO games(cateID ,time,users,active)
select '2','2','0','1'
where (SELECT count(*) FROM `games` WHERE cateID=2 AND active=1) <= 0

仍然出错。

2 个答案:

答案 0 :(得分:0)

试试这个

DECLARE
  games_count INTEGER;
BEGIN
  SELECT count(*) FROM `games` WHERE cateID=2 AND active=1 ;
  IF games_count = 0 THEN
    INSERT INTO games(cateID ,time,users,active) VALUES ('2', '1', '0', '1');
  END IF;
END;

答案 1 :(得分:0)

在执行插入之前,请检查选择查询。如果select查询返回0记录,则插入查询时不会插入任何内容。

select  cateID,'2' as time,'0' as users,active 
FROM 
   (select count(*) as countRecord,cateID,active 
    from games 
    where  CATEID=2 and active=1 group by cateID,active) G   
where countRecord <= 0  
group by cateID, active,time,users