判断数据库中表内数据为空的办法

我们的数据库是数据同步过来的 有时候某些表会失败,数据没有过来,每天都要自己打开数据库 一个个点点点 看看哪个表没有成功 再同步一次 表如果多的话 有点麻烦了

检测数据库表为空的MYSQL语句

SELECT
    TABLE_NAME 
FROM
TABLES 
WHERE
    TABLE_SCHEMA = '你要的数据库名字' 
    AND table_rows = 0 
ORDER BY
    table_name;

现在变成了每天执行这个查询语句? 那我每天还要去执行? 我还是做个命令出来吧

做成命令


<?php

namespace App\Console\Commands\Fund;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class TableNullCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'table:null';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取数据库中表数据为空的表名';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->output->title('正在检测数据库表内数据为空的表');
        config(['database.connections.fund.database'=>'information_schema']);
        $result=DB::connection('fund')->select("
        SELECT
    TABLE_NAME
FROM
TABLES
WHERE
    TABLE_SCHEMA = '你要的数据库名字'
    AND table_rows = 0
ORDER BY
    table_name;
        ");
        $count=count($result);
        if ($count==0) {
            $this->output->success('无表内数据为空的数据表,检测完毕,为您退出');
            return ;
        }

        if ($count>0) {
            $tableName=array_column($result, 'TABLE_NAME');
            $tableName=implode(',', $tableName);
            $this->output->success("检测到 $count 表内数据为空的数据表  $tableName 正在为您通知到指定的频道,请稍等");
            Artisan::call('business:notify', [
                '--text' => "检测到有 $count 个表数据为空: $tableName"
            ]);
            $this->output->success("命令完成,为您退出");
        }
    }
}


注册命令 每天9点跑命令,自动通知

 protected $commands = [
     TableNullCommand::class
 ]
$schedule->command('table:null')->timezone('Asia/Shanghai')->dailyAt('09:00'); 

结果

判断数据库中表内数据为空的办法

本作品采用《CC 协议》,转载必须注明作者和本文链接
chowjiawei
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 6

做的很赞,你这个自动通知是发送到微信吗?

2年前 评论
人艰不拆 2年前
chowjiawei (楼主) 2年前

mq 不就好了 失败重试, 再加一个报错的预警

2年前 评论
chowjiawei (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!