SQL SELECT查询 - 忽略空/ NULL字段

时间:2015-08-24 10:27:40

标签: php mysql sql

这是我的疑问:

SELECT  *
FROM    `fruit`
WHERE ingredient1 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
OR ingredient2 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
OR ingredient3 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
OR ingredient4 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
OR ingredient5 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')

变量要么只是名称本身($ Aardbei是' Aardbei',$ Appel是' Appel'等等)或是空的(如'&# 39;,实际上没有设置或NULL) 有问题的表格可以包含'成分'字段为空,如果变量也为空,则匹配,这不是我想要的。

如何才能使查询中的空变量被忽略,而不是匹配SQL表中的空字段?

2 个答案:

答案 0 :(得分:0)

您的问题的直接答案是修复表,使其包含NULL值而不是空字符串值。您可以一次性执行此操作:

update fruit
    set ingredient1 = nullif(ingredient1, ''),
        ingredient2 = nullif(ingredient2, ''),
        . . .;

由于NULL与任何内容都不匹配,因此与''不匹配。

我应该指出,你可以在where

中做同样的事情
where nullif(ingredient1, '') in . . . or
      nullif(ingredient2, '') in . . .

但更好的答案是,在SQL中,多列代表值的“数组”并不是一个好的设计。相反,您需要一个FruitIngredients表,每行FruitIngredient一行。这也可以简化您的查询。

答案 1 :(得分:0)

按以下方式使用 -

SELECT  *
FROM    `fruit`
WHERE ingredient1 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
OR ingredient2 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
OR ingredient3 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
OR ingredient4 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
OR ingredient5 IN ('$Aardbei','$Appel','$Banaan','$Mango','$Perzik','$Sinaasappel','$Peer','$Pruim','$Kiwi')
AND ingredient1<>'' AND ingredient2<>'' AND ingredient3<>'' AND ingredient4<>'' AND ingredient5<>'';