利用REGEXP函数,可以解决你的问题
用于搜索
来自
$list = 'aapl:us,spy:us,intc:us,goog:us';
到
$list = '(^|,)aapl:us|spy:us|intc:us|goog:us(,|$)';
# OR without modifying your list just replace comma with pipe
$list = 'aapl:us,spy:us,intc:us,goog:us';
$list = '(^|,)'.str_replace(',', '|', $list).'(,|$)';
和
来自
$query = "SELECT * FROM table WHERE ticker ".$pha;
到
$query = "SELECT * FROM table WHERE ticker REGEXP $list";
这将是
SELECT * FROM table WHERE ticker REGEXP (^|,)aapl:us|spy:us|intc:us|goog:us(,|$)
为了让特定数量的股票创建查询字符串,如下所示
SELECT *,((ticker REGEXP '(^|,)aapl:us(,|$)') + (ticker REGEXP '(^|,)spy:us(,|$)') ) as sum
FROM
table
HAVING sum = 2
测试总和以了解我们在做什么
mysql> -- test variable
mysql> set @test='aapl:us,spy:us,intc:us,goog:us';
Query OK, 0 rows affected (0.00 sec)
mysql> -- variable contents
mysql> select @test;
+--------------------------------+
| @test |
+--------------------------------+
| aapl:us,spy:us,intc:us,goog:us |
+--------------------------------+
1 row in set (0.00 sec)
mysql> -- if you create sum it can be used in having clause
mysql> select ((@test REGEXP '(^|,)aapl:us(,|$)') + (@test REGEXP '(^|,)spy:us(,|$)') ) as sum;
+------+
| sum |
+------+
| 2 |
+------+
1 row in set (0.00 sec)
mysql> -- for 2 ticker
mysql> select * from( select ((@test REGEXP '(^|,)aapl:us(,|$)') + (@test REGEXP '(^|,)spy:us(,|$)') ) as sum ) as q having sum =2;
+------+
| sum |
+------+
| 2 |
+------+
1 row in set (0.00 sec)
mysql> -- for 3 or more ticker
mysql> select * from( select ((@test REGEXP '(^|,)aapl:us(,|$)') + (@test REGEXP '(^|,)spy:us(,|$)') ) as sum ) as q having sum >=3;
Empty set (0.00 sec)
生成查询的脚本
akshay@db-3325:/tmp$ cat test.php
<?php
$list = 'aapl:us,spy:us,intc:us,goog:us';
$sum = '('.implode("+", array_map(function($v){ return sprintf("(ticker REGEXP '(^|,)%s(,|$)')",$v); },explode(",",$list))).')';
$query = "SELECT *, $sum as sum from table having sum = 2";
print $query.PHP_EOL;
?>
输出
akshay@db-3325:/tmp$ php test.php
SELECT *, ((ticker REGEXP '(^|,)aapl:us(,|$)')+(ticker REGEXP '(^|,)spy:us(,|$)')+(ticker REGEXP '(^|,)intc:us(,|$)')+(ticker REGEXP '(^|,)goog:us(,|$)')) as sum from table having sum = 2