MySQL执行查询的速度太慢

时间:2016-12-22 10:22:17

标签: mysql performance

我有一张桌子" user_values"超过20百万行。 表格如下:

id | user_id |      scan_date      | value | category |      user_date      | 

1  |    1    | 2016-12-10 10:10:10 |  10   |    1     | 2016-01-05 11:11:11 | 
2  |    2    | 2016-12-10 10:10:10 |  14   |    2     | 2016-02-06 12:12:12 | 
3  |    3    | 2016-12-10 10:10:10 |  15   |    2     | 2016-03-07 13:13:13 | 
4  |    1    | 2016-12-10 12:10:10 |  11   |    1     | 2016-01-05 10:10:10 | 
5  |    2    | 2016-12-10 12:10:10 |  13   |    2     | 2016-02-06 12:12:12 | 
6  |    3    | 2016-12-10 12:10:10 |  17   |    2     | 2016-03-07 13:13:13 | 
7  |    1    | 2016-12-10 14:10:10 |  13   |    1     | 2016-01-05 11:11:11 | 
8  |    2    | 2016-12-10 14:10:10 |  15   |    2     | 2016-02-06 12:12:12 | 
9  |    3    | 2016-12-10 14:10:10 |  16   |    2     | 2016-03-07 13:13:13 | 
10 |    1    | 2016-12-10 16:10:10 |  18   |    1     | 2016-01-05 11:11:11 | 
11 |    2    | 2016-12-10 16:10:10 |  13   |    2     | 2016-02-06 12:12:12 | 
12 |    3    | 2016-12-10 16:10:10 |  14   |    2     | 2016-03-07 13:13:13 | 

" scan_date"是写行的时候。

Mysql每天在这张表中写下大约1百万行。

我有一个SELECT QUERY来获取最后一个'值'对于每个用户:

SELECT * FROM (SELECT * FROM user_values 
        WHERE
        category =  '2' AND
        user_date      >=  '2016-01-16' AND
        user_date      <= '2016-12-15 10:34:35' 
        ORDER BY id DESC LIMIT 999999999) as user_values
        WHERE 
        category = '2' AND
        user_date      >=  '2016-01-16' AND
        user_date      <= '2016-12-15 10:34:35' 
        GROUP BY user_values.user_id

查询是我找到的更快但现在我得到了错误&#34; MySQL服务器已经消失了#34;因为查询太慢了。

我也尝试创建分区:哈希(id)分区100个,但我没有解决,我认为现在比较慢。

有人建议我购买功能强大的服务器,但我认为我无法解决问题。 有人建议我创建一个mysql&#34; cluster&#34;主/从

您有其他建议或更好的查询或更好的mysql配置吗?

2 个答案:

答案 0 :(得分:0)

mysqli

中的数据库中获取最后一个插入ID
$jobs = Post::whereHas('skills', function ($query) {
    foreach($skills as $skill) {
        $query->where('name', '=', $skill);
    }
})->get();

使用上一个用户ID获取值

$sql = "YOUR INSERT QUERY";
if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
}

通过PDO获取上次插入ID

$sql2 = "SELECT `value` FROM tablename where `id`=$last_id ; 
$value = $conn->query($sql2);
echo "Value of last user is $value"

使用上一个用户ID获取值

    $sql = "YOUR INSERT QUERY";
    $conn->exec($sql);
    $last_id = $conn->lastInsertId();

答案 1 :(得分:0)

id | select_type | table      | type| possible_keys      | key      | key_len | ref   | rows | filtered | Extra                                       |
1  |  PRIMARY    | <derived2> | ALL | NULL               | NULL     | NULL    | NULL  | 53604| 100.00   | Using where; Using temporary; Using filesort|

2  |  DERIVED    |users_values| ref | category,user_date | category | 4       | const | 53604| 100.00   | Using where; Using filesort