如何使用CASE..WHEN检查子查询结果?

时间:2017-07-20 12:19:12

标签: mysql sql

这是我的问题:

INSERT INTO mytable(questin_id)
SELECT t1.id
FROM qanda t1 
WHERE (EXISTS (SELECT 1 
               FROM qanda t2 
               WHERE ID = :id 
                 and t1.ID = t2.related)
           or t1.id = :id)
  and Type = 0;

SELECT语句返回id,并将其插入mytable。一切都很好。但有时WHERE子句上的条件不匹配任何内容,SELECT语句不返回任何内容,因此不会插入任何内容。虽然我总是需要插入一个新行。所以我想检查SELECT语句是否匹配,然后它应该返回null。这是我的新查询:

INSERT INTO mytable(questin_id)
SELECT CASE WHEN EXISTS(t1.id) THEN t1.id ELSE NULL END
FROM qanda t1 
WHERE (EXISTS (SELECT 1 
               FROM qanda t2 
               WHERE ID = :id 
                 and t1.ID = t2.related)
           or t1.id = :id)
  and Type = 0;

但它没有按预期工作。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果您总想插入1个值,则可以使用聚合:

INSERT INTO mytable(questin_id)
    SELECT MAX(t1.id)
    FROM qanda t1 
    WHERE (EXISTS (SELECT 1 
                   FROM qanda t2 
                   WHERE t2.ID = :id AND
                         t1.ID = t2.related
                  ) OR
           t1.id = :id
          ) AND
          Type = 0;

当然,这将只返回一行,即使逻辑(除了MAX())将返回多行。