<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>MySQL on seth-shi</title><link>https://sethix.com/tags/mysql/</link><description>Recent content in MySQL on seth-shi</description><generator>Hugo -- gohugo.io</generator><language>en</language><lastBuildDate>Sun, 25 Jun 2023 14:14:01 +0800</lastBuildDate><atom:link href="https://sethix.com/tags/mysql/index.xml" rel="self" type="application/rss+xml"/><item><title>Force Returning Empty Data When MySQL Unexpectedly Crashes in Laravel</title><link>https://sethix.com/posts/2023062514/</link><pubDate>Sun, 25 Jun 2023 14:14:01 +0800</pubDate><guid>https://sethix.com/posts/2023062514/</guid><description>Background We previously encountered an issue where the service completely crashed when MySQL went down, with Redis failing to handle any requests. The normal business query logic is: Get data from Redis first, return if available If Redis has no data, query MySQL Write the retrieved data to Redis Return data Problem Analysis Redis itself wasn&amp;rsquo;t the issue - the problem occurred at step 2 When querying MySQL with the database service down, requests get blocked Blocking timeout leads to exceptions, preventing step 3 from executing Subsequent requests continue trying to connect to MySQL, creating infinite blocking that overloads the application servers Solution Our solution (may not fit all scenarios): Force caching empty data in Redis when MySQL crashes, allowing partial empty responses instead of service failure Implementation Approach Set appropriate MySQL connection timeout mysqlnd.</description></item><item><title>Accessing Internal Network MySQL Database Locally via MobaXterm Xshell Tunneling</title><link>https://sethix.com/posts/2023020814/</link><pubDate>Wed, 08 Feb 2023 14:50:58 +0800</pubDate><guid>https://sethix.com/posts/2023020814/</guid><description>Context The test environment database resides in an internal network, while my computer can only connect via a jump server. To enable local code access, I tested MobaXterm for SSH tunneling.
Installation Download the free version from the official site: https://mobaxterm.mobatek.net/download.html 1.png Choose between the portable version (no installation) or installer. I selected the installer for straightforward setup. 2.png Configuration Open MobaXterm, navigate to Tunneling &amp;gt; New SSH tunnel 3.png Configure three key sections: ① Internal database server IP/port ② Jump server SSH credentials (IP, user, port) ③ Local port (choose an unused port) 4.</description></item><item><title>Optimizing Database Queries to Reduce MySQL Load to 1%</title><link>https://sethix.com/posts/2022060916/</link><pubDate>Thu, 09 Jun 2022 16:59:31 +0800</pubDate><guid>https://sethix.com/posts/2022060916/</guid><description> Following the previous Redis incident, our monitoring system recently alerted about abnormal MySQL load in the advertising system The Ops team asked me to investigate whether recent code changes caused the database load spike. As shown: Database The graph clearly shows a sudden load surge at the marked timestamp, which persisted without subsiding Checking Git commit history revealed no deployments on that day, indicating operational configuration changes might be the culprit Accessed Alibaba Cloud&amp;rsquo;s SQL Audit and Analysis feature (similar solutions exist on other cloud platforms): SQL Audit The problematic SQL query was quickly identified, accounting for over 90% of total queries Next steps were straightforward: Locate the corresponding code for this SQL Root cause analysis: Original code handled single configurations, but recent operational changes allowed multiple options No caching implementation Optimized query logic and added caching mechanisms Database Database Post-optimization showed reduced database load, but another SQL query became prominent with higher average latency due to WHERE EXISTS usage: The Laravel whereHas method generated inefficient WHERE EXISTS queries GitHub solutions suggested using WHERE IN instead Implemented custom solution using these patterns (alternative packages available): laravel-wherehasin hasin eloquent-has-by-non-dependent-subquery Database Database Final optimizations resulted in: Balanced query distribution Database load reduced to 1% (compared to ~50% previously) Consistent performance during peak periods</description></item><item><title>MySQL Partitioning Practice</title><link>https://sethix.com/posts/2021082715/</link><pubDate>Fri, 27 Aug 2021 15:46:03 +0800</pubDate><guid>https://sethix.com/posts/2021082715/</guid><description>While I&amp;rsquo;ve read many related articles before, true understanding comes from practice. Recently, the data team restructured logging formats. I designed a table schema and asked them to write cleaned client logs into it. As this is a video playback statistics table, we implemented date-based partitioning. With less than 100k videos in the library, we opted for monthly partitioning instead of daily. For auto-increment primary key id, you must create composite primary key with partitioning key In our actual implementation, we simply omitted the primary key `id` BIGINT UNSIGNED NOT NULL auto_increment, PRIMARY KEY(`id`, `date_key`) Partition by month Other playback statistics fields are omitted Records before 2021-09-01 will be stored in p_202108 partition Records from 2021-09-01 to 2021-09-30 will go to p_202109 partition CREATE TABLE `video_play_logs` ( `video_id` INT UNSIGNED NOT NULL, `date_key` date NOT NULL, index `video_play_logs_video_id_index` ( `video_id` ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci PARTITION BY RANGE(to_days(`date_key`)) ( PARTITION p_202108 VALUES LESS THAN (to_days(&amp;#39;20210901&amp;#39;)), PARTITION p_202109 VALUES LESS THAN (to_days(&amp;#39;20211001&amp;#39;)), PARTITION p_202110 VALUES LESS THAN (to_days(&amp;#39;20211101&amp;#39;)), PARTITION p_202111 VALUES LESS THAN (to_days(&amp;#39;20211201&amp;#39;)), PARTITION p_202112 VALUES LESS THAN (to_days(&amp;#39;20220101&amp;#39;)) ) Verify partition configuration Insert test data and check TABLE_ROWS for record counts in each partition SELECT TABLE_NAME, PARTITION_NAME, TABLE_ROWS FROM information_schema.</description></item><item><title>A Slow API Incident Leading to Database Query Testing and Fully Automated API Test Assertions</title><link>https://sethix.com/posts/2021072215/</link><pubDate>Thu, 22 Jul 2021 15:08:54 +0800</pubDate><guid>https://sethix.com/posts/2021072215/</guid><description>Today during client-side testing, feedback indicated a slow API response. With the responsible colleague on leave, I investigated the project and confirmed the issue.
Added SQL logging in the controller: # SQL logging DB::listen(fn(QueryExecuted $query) =&amp;gt; Log::info($query-&amp;gt;sql)); # Log output [2021-07-22 12:46:15] local.INFO: select * from `albums` where `albums`.`id` = ? and `albums`.`deleted_at` is null limit 1 ... (repeated 24 times) The logs revealed multiple identical queries - a classic N+1 problem caused by missing eager loading Database query pseudocode: class Controller { public function index() { $models = Model::query()-&amp;gt;limit(20)-&amp;gt;get(); return ModelsResource::collection($models); } } class ModelsResource extends JsonResource { public function toArray($request) { return [ &amp;#39;id&amp;#39; =&amp;gt; $this-&amp;gt;id, &amp;#39;name&amp;#39; =&amp;gt; $this-&amp;gt;title, &amp;#39;album_id&amp;#39; =&amp;gt; $this-&amp;gt;album_id, // Problematic line &amp;#39;album_name&amp;#39; =&amp;gt; $this-&amp;gt;album-&amp;gt;title, ]; } } The resource accessed the album relationship without eager loading Solution: Add eager loading $models = Model::query()-&amp;gt;with(&amp;#39;album&amp;#39;)-&amp;gt;limit(20)-&amp;gt;get(); Prevention Strategies Problem detection is costly - better to prevent through automation Implemented HTTP testing with SQL query monitoring in base TestCase: public function json($method, $uri, array $data = [], array $headers = []) { $maxCount = 10; DB::enableQueryLog(); $response = parent::json($method, $uri, $data, $headers); $queries = collect(DB::getQueryLog())-&amp;gt;pluck(&amp;#39;query&amp;#39;); $this-&amp;gt;assertLessThan( $maxCount, $queries-&amp;gt;count(), sprintf(&amp;#34;Endpoint:%s[%s], SQL:%d\r\n%s&amp;#34;, $uri, $method, $maxCount, $queries-&amp;gt;implode(&amp;#34;\r\n&amp;#34;)) ); DB::flushQueryLog(); return $response; } Enhanced validation using unique query comparison: $duplicateQueries = $queries-&amp;gt;count() - $queries-&amp;gt;unique()-&amp;gt;count(); $this-&amp;gt;assertLessThan($maxDuplicates, $duplicateQueries, &amp;#34;Excessive duplicate queries&amp;#34;); Route coverage validation via custom test suite: &amp;lt;testsuite name=&amp;#34;End&amp;#34;&amp;gt; &amp;lt;file&amp;gt;tests/EndApiTest.</description></item><item><title>Why Timestamp in MySQL Handles Time Zones Automatically</title><link>https://sethix.com/posts/2020120917/</link><pubDate>Wed, 09 Dec 2020 17:30:25 +0800</pubDate><guid>https://sethix.com/posts/2020120917/</guid><description>I&amp;rsquo;ve long been curious why MySQL&amp;rsquo;s timestamp type can effortlessly handle time zone issues. In practical use with Laravel frameworks, Migration files default to timestamp fields without requiring special attention.
Getting Started Check current database time zone settings mysql&amp;gt; show variables like &amp;#34;%time_zone%&amp;#34;; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | CST | | time_zone | +08:00 | +------------------+--------+ 2 rows in set (0.30 sec) View table structure mysql&amp;gt; desc timestamp_test; +--------------+-----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-----------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | created_time | datetime | YES | | NULL | | | created_at | timestamp | YES | | NULL | | +--------------+-----------+------+-----+---------+----------------+ 3 rows in set (0.</description></item><item><title>MySQL Reverse Fuzzy Lookup</title><link>https://sethix.com/posts/2018040121/</link><pubDate>Sun, 01 Apr 2018 21:56:48 +0800</pubDate><guid>https://sethix.com/posts/2018040121/</guid><description>When developing a WeChat auto-reply demo, I encountered this scenario:
Receive specific messages Reply with predefined content based on keywords stored in database Requires partial matching with fuzzy database queries For conventional fuzzy matching, everyone knows to use LIKE. Given this table structure:
id keyword reply 1 David This is David 2 KingDavid This is David If the input keyword is &amp;ldquo;David&amp;rdquo;, we need to find all records containing David. The SQL would be:</description></item><item><title>Quickly Set Up an LNMP Environment</title><link>https://sethix.com/posts/2018033111/</link><pubDate>Sat, 31 Mar 2018 11:55:27 +0800</pubDate><guid>https://sethix.com/posts/2018033111/</guid><description>Environment Specifications Linux version: CentOS7 Nginx: Default version MySQL: MariaDB PHP: Version PHP71 Linux Open required ports after server setup: 80 for HTTP 443 for HTTPS (optional) 3306 for remote MySQL connections Nginx Install Nginx on CentOS: yum install nginx -y Start Nginx: nginx Enable auto-start: systemctl enable nginx Configuration: Default config file: /etc/nginx/nginx.conf Add include /etc/nginx/conf.d/*.conf; to load custom configurations Remove default server block and create new config: vi /etc/nginx/conf.</description></item></channel></rss>