Sphinx实现复杂Sql查询语句

Sphinx可以实现复杂的Sql语句,具体操作如下:

比如要实现的Sql语句为:select * from new_notes where ((status=100 &tmp_edit_status = 1) or status = 200 or status = 800 )  and title LIKE '%测试%' and tmptype = 1 and create_time > 1000 and create_time < 9999999 order by create_time limit 0,10 

1.首先设置匹配模式:Sphinx的匹配格式有哪些可参见https://www.cnblogs.com/yuanwanli/p/12768490.html

$sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);

2.配置取值区间:

$sphinx->SetFilterRange('create_time',1000,'9999999');#可以设置多个

3.配置排序字段:

$sphinx->SetSortMode(SPH_SORT_EXTENDED,'create_time DESC');
#设置排序字段及排序方式,第一个参数是排序的模式,第二个参数为字段和排序方式DESC或ASC 注意:字段和排序方式需要空格隔开

4.设置limit:

$sphinx->SetLimits(0, 10, 1000);

5.设置查询关键词:最为关键的一步

$result = $sphinx -> query('((@status=100 & @tmp_edit_status=1) | @status=200  | @status=800 ) & @title(测试) & @tmptype = 1 ‘,"notes"); 
#语法 query('关键词或语句','索引名称')
#语句的语法:@字段名 判断条件 
#模糊查询:@字段名(关键词) #多个判断条件之间用 & 或 | 连接

完整代码如下:

$sphinx = new SphinxClient();
$sphinx->SetServer("xxx.xxx.xx.xx",xxx);
$sphinx->SetMatchMode(SPH_MATCH_EXTENDED2);
$sphinx->SetFilterRange('create_time',1000,'9999999');
$sphinx->SetSortMode(SPH_SORT_EXTENDED,'create_time DESC');
$sphinx->SetLimits(0, 10, 1000);
$sphinx->SetArrayResult(true);
$result = $sphinx -> query('((@status=100 & @tmp_edit_status=1) | @status=200  | @status=800 ) & @title(测试) & @tmptype = 1 ‘,"notes"); 
echo "Query failed: " . $sphinx->GetLastError() . ".\n";
echo json_encode($result);

这样就可以实现复杂Sql查询语句了!

猜你喜欢

转载自www.cnblogs.com/yuanwanli/p/12907911.html