我面临着一个两难的境地,我必须根据参数构建一个字符串。
CASE gender_Case
WHEN CONCAT("1") THEN
SET @tempString = CONCAT('M');
WHEN CONCAT("2") THEN
SET @tempString = CONCAT('F');
ELSE
SET @tempString = CONCAT('M','F');
END CASE;
我要构建的查询是:
SELECT @uid:=uid FROM search_optimized_table where country = country
and uid !=userId and TIMESTAMPDIFF(YEAR,DOB,CURDATE())
BETWEEN minAge and maxAge and gender IN (@tempString)
对于案例1和2工作正常。 但除了案例1和案例2.它只是失败。
知道怎么解决吗?
情景:
当来电者收到案例1时,它会为性别IN创建查询 (M)。但在我的问题中,案例3总是失败。
编辑:
CASE gender_Case
WHEN CONCAT("1") THEN
SET @tempString = "M";
WHEN CONCAT("2") THEN
SET @tempString = "F";
ELSE
SET @tempString = "M,F";
END CASE;
上面的第一个和第二个有效,但不是第三个。
答案 0 :(得分:0)
请按以下方式尝试查询部分,如果有效则让我工作:
CASE WHEN gender_Case="1" THEN SET @tempString = "'M'";
WHEN gender_Case="2" THEN SET @tempString = "'F'";
ELSE SET @tempString = "'M','F'";
END;
SET @Query = CONCAT("SELECT @uid:=uid FROM search_optimized_table where country = country
and uid !=userId and TIMESTAMPDIFF(YEAR,DOB,CURDATE())
BETWEEN minAge and maxAge and gender IN (",@tempString,") ");
PREPARE stmtForQuery FROM @Query;
EXECUTE stmtForQuery;
DEALLOCATE PREPARE stmtForQuery;
(注意:我们在MySql中有两种CASE语法。一种是你实现的方式,另一种是这一种。这没有任何区别。我改变的是你将用于参数的字符串IN。)
答案 1 :(得分:0)
为什么没有2个温度串?
IF GENDER_CASE = 1 THEN
SET @ASTRING = 'M';
SET @BSTRING = 'M';
ELSEIF GENDER_CASE = 2 THEN
SET @ASTRING = 'F';
SET @BSTRING = 'F';
ELSE
SET @ASTRING = 'M';
SET @BSTRING = 'F';
END IF;
答案 2 :(得分:0)
我必须在查询本身使用concat将整个查询更改为其他版本。 对于这种情况:
CASE gender_Case
WHEN CONCAT("1") THEN
SET @tempString = "gender IN ('M')";
WHEN CONCAT("2") THEN
SET @tempString = "gender = ('F')";
ELSE
SET @tempString = "gender IN ('M','F')";
END CASE;
用于查询构建:
SET @query = CONCAT('INSERT INTO temp_local_search(
SELECT @uid:=uid FROM search_optimized_table
where country = ',country,' and uid !=',userId,' and
TIMESTAMPDIFF(YEAR,DOB,CURDATE()) BETWEEN ',minAge,' and ',maxAge,' and ',@tempString,';');