MySql data and table structure operation SQL

1. Tasks

insert image description here


  • result backup
1. ALTER TABLE result RENAME TO result_2021_8;
2. CREATE TABLE result  LIKE   result_2021_8
  • result_ddr backup
1. ALTER TABLE result_ddr RENAME TO result_ddr_2021_8;
2. CREATE TABLE result_ddr LIKE  result_ddr_2021_8
  • php application
	//测试ddr失败设备数据统计
	public function  backupFaildDdrData(){
			
			$total = $this -> getDdrTotal(-1,-1,null);
			if($total < MAX_TABLE_ROWNUM){
   
   //总数据不超过120w,数据不需要备份和重置!
			  return array('code'=>-2,'total'=>$total);	
			}	
			$dataStr = date('Y')."_".date('m');
			$sqlTbExist = "SHOW TABLES LIKE  'result_ddr_$dataStr';";
			$resTbExist= $this->db_getOne($sqlTbExist);
			if(!$resTbExist){
				//重命名表 result_ddr
				$sqlRename = "ALTER TABLE result_ddr RENAME TO result_ddr_$dataStr";
				$code = $this->db_update($sqlRename);
				//复制表结构
				if($code){
					$sqlCopy = "CREATE TABLE result_ddr LIKE result_ddr_$dataStr";
					$this->db_query($sqlCopy);
				}
				return array('code'=>1,'total'=>$total);
			}else{
				return array('code'=>-3,'total'=>$total);
			}
 		
	}


2. SQL scenario

1. Only copy the table structure to the new table

CREATE TABLE new table SELECT * FROM old table WHERE 1=2

or CREATE TABLE new table LIKE old table

2. Copy the table structure and data to the new table

CREATE TABLE new table SELECT * FROM old table

This method will copy all the content in oldtable, of course we can use delete from newtable; to delete.

However, one of the worst parts of this method is that the new table does not have the primary key, Extra (auto_increment) and other attributes of the old table. You need to use "alter" to add it yourself, and it is easy to make mistakes.

3. Copy the data from the old table to the new table (assuming the two tables have the same structure)

INSERT INTO new table SELECT * FROM old table

4. Copy the data from the old table to the new table (assuming the two tables have different structures)

INSERT INTO new table (field 1, field 2, ...) SELECT field 1, field 2, ... FROM old table

5. You can copy the structure of Table 1 to Table 2

SELECT * INTO table2 FROM table1 WHERE 1=2

6. You can copy all the contents of Table 1 to Table 2

SELECT * INTO table 2 FROM table 1

10. The tables are not in the same database (eg, db1 table1, db2 table2)

sql: insert into db1.table1 select * from db2.table2 (full copy)
insert into db1.table1 select distinct * from db2.table2 (do not copy duplicate records)
insert into tdb1.able1 select top 5 * from db2.table2 (first five records)

11. Rename table

ALTER TABLE result_ddr RENAME TO result_ddr_9;

Guess you like

Origin blog.csdn.net/oZiJing/article/details/119750439