代码之家  ›  专栏  ›  技术社区  ›  GYaN user7305435

空结果时选择查询返回错误

  •  1
  • GYaN user7305435  · 技术社区  · 8 年前

    我正在使用 SELECT 在下面给出的查询中查询为子查询。。。

    SELECT COUNT (`Notification`.`id`) AS `count`
    FROM `listaren_mercury_live`.`notifications` AS `Notification`
    WHERE NOT FIND_IN_SET(`Notification`.`id`,(SELECT read_ids FROM read_notifications WHERE user_id = 46))
    AND((notisfication_for IN("all","India"))
    OR(FIND_IN_SET(46,notification_for))
    

    此查询在以下情况下工作正常

    SELECT read_ids FROM read_notifications WHERE user_id = userid)
    

    返回结果,如21,22,23,24

    但当此查询返回空时。

    结果id 0 而不是 3 .用户有3个未读通知;所以结果一定是 3.

    问题

    当内部select查询返回

    12,42 
    

    但如果查询返回null,则整个查询的结果将变为0。

    查询的预期结果

    Expected Result

    我得到的结果

    Result I'm getting

    我只想知道子查询是否返回空值。然后查询 (Notification.id,(从read\u notifications中选择read\u id,其中user\u id)=46) 结果如下所示

     (`Notification`.`id`,(0))
    

    而不是

    (`Notification`.`id`,())
    

    所以它会正常工作

    请告诉我这方面需要什么改进。

    谢谢

    1 回复  |  直到 8 年前
        1
  •  1
  •   Nick SamSmith1986    8 年前

    尝试替换

    FIND_IN_SET(`Notification`.`id`,(SELECT read_ids FROM read_notifications WHERE user_id = 46))
    

    具有

    FIND_IN_SET(`Notification`.`id`,IFNULL((SELECT read_ids FROM read_notifications WHERE user_id = 46), ''))
    

    从 manual ,如果子查询结果为空,它将返回NULL,并且 FIND_IN_SET will return NULL if either argument is NULL 和 NOT NULL is still NULL, as is NULL AND 1, and NULL is equivalent to false 因此,当子查询返回NULL时,WHERE条件将失败。

    通过在子查询结果周围添加IFNULL,可以让它返回一个对FIND\u IN\u SET有效的值,这将允许您的查询按预期工作。