如何使用带有in()函数的mysql存储函数返回的值?

时间:2011-12-01 12:34:40

标签: mysql sql stored-functions

我有一个名为'dealBusinessLocations'的字段(在表'dp_deals'中),其中包含逗号分隔格式的另一个表(dp_business_locations)的ID。

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)));

我也尝试过将静态值用于函数arguments,但没有用

select * from dp_deals as d left join dp_business_locations as b on(b.businessLocID IN (BusinessList('21,22')));

使用函数返回的值似乎存在一些问题。

3 个答案:

答案 0 :(得分:3)

首先,请阅读:

<强> Is storing a comma separated list in a database column really that bad?
Yes, it is

然后,去规范你的表格。


现在,如果你真的不能这样做,或者在你正常化之前,请使用 FIND_IN_SET() 功能:

select * 
from dp_deals as d 
  left join dp_business_locations as b 
    on FIND_IN_SET(b.businessLocID, d.dealBusinessLocations)

然后,再次阅读该文章。如果查询速度很慢或者您对此表有其他问题,那么您就会知道原因:

<强> Is storing a comma separated list in a database column really that bad?
Yes, it is

答案 1 :(得分:2)

简单,请改用find_in_set()

SELECT * 
FROM dp_deals as d 
LEFT JOIN dp_business_locations as b 
       ON (FIND_IN_SET(b.businessLocID,d.dealBusinessLocations) > 0); 

请参阅:http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

请注意,如果你删除CSV并离开地狱,你可以使用简单的连接:

SELECT d.*, GROUP_CONCAT(b.dealBusinessLocation) as locations
FROM dp_deals as d 
LEFT JOIN dp_business_location as b 
       ON (d.dealBusinessLocation = b.businessLocID); 

这将更加快速和标准化为奖金。

答案 2 :(得分:0)

我认为你的问题是IN()不希望得到一个包含大量字段的字符串,但是有很多字段。

使用您的功能,您可以发送此信息:

WHERE something IN ('\'21\',\'22\''); /* i.e. a single text containing "'21','22'" */

而不是预期的

WHERE something IN ('21','22');