我有一個名爲'dealBusinessLocations'的字段(在一個表'dp_deals'中),它包含以逗號分隔的格式的另一個表(dp_business_locations)的一些ID。如何使用in()函數使用從mysql存儲函數返回的值?
dealBusinessLocations
----------------------
0,20,21,22,23,24,25,26
我需要在查詢的in()函數內使用這個值。
像
select * from dp_deals as d left join dp_business_locations as b on(b.businessLocID IN (d.dealBusinessLocations) ;
正弦MySQL不支持任何字符串爆炸功能,我創建了一個存儲功能
delimiter //
DROP FUNCTION IF EXISTS BusinessList;
create function BusinessList(BusinessIds text) returns text deterministic
BEGIN
declare i int default 0;
declare TmpBid text;
declare result text default '';
set TmpBid = BusinessIds;
WHILE LENGTH(TmpBid) > 0 DO
SET i = LOCATE(',', TmpBid);
IF (i = 0)
THEN SET i = LENGTH(TmpBid) + 1;
END IF;
set result = CONCAT(result,CONCAT('\'',SUBSTRING(TmpBid, 1, i - 1),'\'\,'));
SET TmpBid = SUBSTRING(TmpBid, i + 1, LENGTH(TmpBid));
END WHILE;
IF(LENGTH(result) > 0)
THEN SET result = SUBSTRING(result,1,LENGTH(result)-1);
END IF;
return result;
END//
delimiter ;
該功能可以正常使用。
mysql> BusinessList('21,22')
BusinessList('21,22')
-----------------------
'21','22'
但是使用該函數的查詢也不起作用。這裏是查詢。
select * from dp_deals as d left join dp_business_locations as b on(b.businessLocID IN (BusinessList(d.dealBusinessLocations)));
我已經使用功能argumet靜態值也嘗試過,但沒有用
select * from dp_deals as d left join dp_business_locations as b on(b.businessLocID IN (BusinessList('21,22')));
似乎有一些問題與使用從函數返回值。
規範化表。在此之前,使用'FIND_IN_SET()'函數。 –