Skip to content

Commit ffc1a6f

Browse files
committed
提交
0 parents  commit ffc1a6f

File tree

2 files changed

+115
-0
lines changed

2 files changed

+115
-0
lines changed

README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
## ShardingQuery
2+
3+
根据时间分表的数据查询类
4+
5+
## 使用方法
6+
7+
ThinkPHP 5
8+
9+
```php
10+
$shardingQuery = new ShardingQuery(
11+
'think\Db::query',
12+
[
13+
'order',
14+
'order_history',
15+
],
16+
'SELECT * FROM {table}',
17+
10,
18+
0
19+
);
20+
$res = $shardingQuery->select();
21+
var_dump($res);
22+
```

ShardingQuery.php

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
<?php
2+
3+
/**
4+
* 根据时间同构分表的查询类
5+
* @author LIUJIAN <coder.keda@gmail.com>
6+
*/
7+
class ShardingQuery
8+
{
9+
10+
/**
11+
* 数据库查询的回调
12+
* 回调必须返回数组类型
13+
* @var callable
14+
*/
15+
public $callback;
16+
17+
/**
18+
* 数据表列表
19+
* 根据顺序查询
20+
* @var array
21+
*/
22+
public $tables;
23+
24+
/**
25+
* 查询语句
26+
* @var string
27+
*/
28+
public $sql;
29+
30+
/**
31+
* 限制数
32+
* @var int
33+
*/
34+
public $limit;
35+
36+
/**
37+
* 偏移数
38+
* @var int
39+
*/
40+
public $offset;
41+
42+
/**
43+
* 数据表的通配符
44+
* @var string
45+
*/
46+
protected static $tableSymbol = '{table}';
47+
48+
/**
49+
* ShardingSelect constructor.
50+
* @param array $tables
51+
* @param callable $callback
52+
* @param string $sql
53+
*/
54+
public function __construct(callable $callback, array $tables, string $sql, int $limit, int $offset)
55+
{
56+
$this->callback = $callback;
57+
$this->tables = $tables;
58+
$this->sql = $sql;
59+
$this->limit = $limit;
60+
$this->offset = $offset;
61+
}
62+
63+
/**
64+
* 执行查询
65+
* @return array
66+
*/
67+
public function select()
68+
{
69+
$data = [];
70+
foreach ($this->tables as $num => $table) {
71+
if (count($data) < $this->limit) {
72+
$limit = $this->limit;
73+
$offset = $this->offset;
74+
if ($num > 0) {
75+
$limit = $this->limit - count($data);
76+
$offset = 0;
77+
}
78+
$sql = "{$this->sql} LIMIT {$limit} OFFSET {$offset}";
79+
$sql = str_replace(static::$tableSymbol, $table, $sql);
80+
$result = call_user_func($this->callback, $sql);
81+
if (empty($result)) {
82+
return $data;
83+
}
84+
$data = array_merge($data, $result);
85+
}
86+
if (count($data) >= $this->limit) {
87+
return $data;
88+
}
89+
}
90+
return $data;
91+
}
92+
93+
}

0 commit comments

Comments
 (0)