WHERE子句仅在IF NOT NULL时

时间:2012-08-15 14:48:21

标签: mysql

我需要SELECT的帮助。

我有一个可以NULL的字段,其中存有一个外键。

SELECT * FROM beerImage WHERE beerBRewID = brewID AND beerBrandID = beerID <--- this can be NULL

所以,如果NULL没有任何反应。

如何检查beerID NOT NULL是否"beerBrandID = beerID",以便我可以使用{{1}}?

5 个答案:

答案 0 :(得分:10)

你可能需要这样的东西:

第一个例子:

SELECT * FROM beerImage WHERE beerBRewID = brewID AND (beerID IS NULL OR beerBrandID = beerID)

第二个例子:

SELECT * FROM beerImage WHERE beerBRewID = brewID AND beerID IS NOT NULL AND beerBrandID = beerID

第一个示例将允许您显示beerID为null的记录以及beerBrandID等于beerID(两者)的啤酒。

第二个将返回与beerBrandID相对应的啤酒(不包括NULL beerID)。

答案 1 :(得分:2)

如果要包含无匹配的记录,则需要外连接

SELECT beer.id AS beerID,
 beer.barrelID AS barrelID,
 beer.imageID AS imageID,
 beer.title AS title,
 beer.map AS map,
 beer.longitude AS longitude, 
 beer.latitude AS latitude, 
 brand.name AS brandName, 
 brew.type AS brewType,
 image.name AS imageName, 
 variation.name AS variationName 
FROM brand, brew, image, beer
LEFT OUTER JOIN variation ON variation.ID = beer.VariationID
WHERE beer.id = %s 
AND md5(beer.memberID) = %s 
AND beer.review = 1 
AND brand.ID = beer.brandID 
AND brew.ID = beer.brewID 
AND image.ID = beer.imageID 

答案 2 :(得分:1)

要检查null / not null,请使用IS NULL / IS NOT NULL

AND beerID IS NOT NULL

答案 3 :(得分:1)

如何在where子句之类的CASE语句中使用

WHERE
CASE WHEN  beer.id IS NOT NULL 
    THEN beer.brand_id = 12345
    ELSE TRUE
END

答案 4 :(得分:0)

您可以使用“IS NULL”或“IS NOT NULL”MySQL比较函数。

在这里阅读更多相关信息: http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_is-null