用户和产品的典型情况,我希望查询返回' false'如果没有为用户分配任何产品但返回为空。
serviceRequest.sql = "SET @productId = ?;\
SELECT IF(product.productId = @productId, 'true', 'false') AS entitled FROM user_token \
INNER JOIN user_product ON user_token.user_id = user_product.user_id \
INNER JOIN product ON user_product.product_id = product.id AND authToken = ? AND product.productId = @productId;";
serviceRequest.values = [request.query.productId, request.query.authToken];
答案 0 :(得分:2)
您的where
条件使其返回空而不是false
。这应该可以使用outer joins
代替:
SELECT IF(ut.user_id IS NOT NULL, 'true', 'false') AS entitled
FROM product p
LEFT JOIN user_product up ON p.id = up.product_id
LEFT JOIN user_token ut ON up.user_id = ut.user_id
AND ut.authToken = ?
WHERE p.productId = @productId;
答案 1 :(得分:0)
您可以使用CASE
声明:
CASE WHEN product.productId IS NULL THEN 'False' ELSE 'True' END