Код ошибки 1146 mysql

I am using windows XP. I am creating a table in phpMyAdmin using its built-in create table feature,
my database name is ddd.

It generates the following code:

CREATE TABLE  `ddd`.`mwrevision` (

`asd` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`sddd` INT NOT NULL
) ENGINE = INNODB;

and the following error shows up:

MySQL said:     
#1146 - Table 'ddd.mwrevision' doesn't exist 

What might be the problem?

mins's user avatar

mins

6,24612 gold badges55 silver badges75 bronze badges

asked Jun 14, 2011 at 10:29

Shaheer's user avatar

9

I also had same problem in past. All had happend after moving database files to new location and after updating mysql server. All tables with InnoDB engine disappeared from my database. I was trying to recreate them, but mysql told me 1146: Table 'xxx' doesn't exist all the time until I had recreated my database and restarted mysql service.

I think there’s a need to read about InnoDB table binaries.

Rafael Barros's user avatar

answered Dec 7, 2011 at 4:43

sempasha's user avatar

sempashasempasha

6235 silver badges18 bronze badges

2

I had the same problem and can’t get a good tip for this over the web, so I shared this for you and for all who needs.

In my situation I copy a database (all files: frm, myd) to the data folder in MySQL data folder (using Wamp at home). All thing was OK until I want to create a table and have the error #1146 Table '...' doesn't exist!.

I use Wamp 2.1 with MySQL version 5.5.16.

My solution:

  1. Export the database to file;

  2. verify if exported file is really OK!!;

  3. drop the database where I have issues;

  4. create a new database with the same name that the last;

  5. import the file to the database.

FOR ME IS PROBLEM SOLVED. Now I can create tables again without errors.

Rafael Barros's user avatar

answered Jan 24, 2012 at 6:30

carlos's user avatar

carloscarlos

1111 silver badge2 bronze badges

1

Restarting MySQL works fine for me.

answered Nov 2, 2014 at 18:24

Muhammad Usman's user avatar

Muhammad UsmanMuhammad Usman

10.3k22 gold badges72 silver badges107 bronze badges

0

In my case I ran this command even if the table wasn’t visible in PhpMyAdmin :

DROP TABLE mytable

then

CREATE TABLE....

Worked for me !

answered May 21, 2015 at 9:22

Jim 007's user avatar

Jim 007Jim 007

3101 gold badge3 silver badges8 bronze badges

1

Check filenames.

You might need to create a new database in phpmyadmin that matches the database you’re trying to import.

Mayur Birari's user avatar

Mayur Birari

5,8378 gold badges34 silver badges61 bronze badges

answered Nov 21, 2012 at 15:23

blarg's user avatar

blargblarg

3,75311 gold badges41 silver badges69 bronze badges

2

I had the same problem. I tried to create a table in mysql and got the same error. I restarted mysql server and ran the command and was able to create/migrate table after restating.

answered May 10, 2013 at 11:10

thekosmix's user avatar

thekosmixthekosmix

1,70320 silver badges34 bronze badges

Today i was facing same problem. I was in very difficult situation but what id did i create a table with diffrent name e.g (modulemaster was not creating then i create modulemaster1) and after creating table i just do the rename table.

answered Jun 12, 2013 at 11:57

Vipin Gurjar's user avatar

I encountered the same problem today. I was trying to create a table users, and was prompted that ERROR 1146 (42S02): Table users doesn't exist, which did not make any sense, because I was just trying to create the table!!

I then tried to drop the table by typing DROP TABLE users, knowing it would fail because it did not exist, and I got an error, saying Unknown table users. After getting this error, I tried to create the table again, and magically, it successfully created the table!

My intuition is that I probably created this table before and it was not completely cleared somehow. By explicitly saying DROP TABLE I managed to reset the internal state somehow? But that is just my guess.

In short, try DROP whatever table you are creating, and CREATE it again.

answered Apr 6, 2015 at 17:51

Xin's user avatar

XinXin

4,3125 gold badges18 silver badges15 bronze badges

As pprakash mentions above, copying the table.frm files AND the ibdata1 file was what worked for me.

In short:

  1. Shut your DB explorer client (e.g. Workbench).
  2. Stop the MySQL service (Windows host).
  3. Make a safe copy of virtually everything!
  4. Save a copy of the table file(s) (eg mytable.frm) to the schema data folder (e.g. MySQL Server/data/{yourschema}).
  5. Save a copy of the ibdata1 file to the data folder (i.e., MySQL Server/data).
  6. Restart the MySQL service.
  7. Check that the tables are now accessible, queryable, etc. in your DB explorer client.

After that, all was well. (Don’t forget to backup if you have success!)

Community's user avatar

answered Aug 17, 2016 at 23:46

SteveCinq's user avatar

SteveCinqSteveCinq

1,9001 gold badge16 silver badges22 bronze badges

Column names must be unique in the table. You cannot have two columns named asd in the same table.

answered Jun 14, 2011 at 10:32

Oswald's user avatar

OswaldOswald

31.1k3 gold badges43 silver badges68 bronze badges

8

run from CMD & %path%=set to mysql/bin

mysql_upgrade -u user -ppassword

answered Jun 14, 2011 at 11:04

Ravi Parekh's user avatar

Ravi ParekhRavi Parekh

5,1249 gold badges45 silver badges58 bronze badges

2

Recently I had same problem, but on Linux Server. Database was crashed, and I recovered it from backup, based on simply copying /var/lib/mysql/* (analog mysql DATA folder in wamp). After recovery I had to create new table and got mysql error #1146. I tried to restart mysql, and it said it could not start. I checked mysql logs, and found that mysql simply had no access rigths to its DB files. I checked owner info of /var/lib/mysql/*, and got 'myuser:myuser' (myuser is me). But it should be 'mysql:adm' (so is own developer machine), so I changed owner to ‘mysql:adm’. And after this mysql started normally, and I could create tables, or do any other operations.

So after moving database files or restoring from backups check access rigths for mysql.

Hope this helps…

thvwns's user avatar

thvwns

3,5483 gold badges41 silver badges57 bronze badges

answered Aug 23, 2013 at 8:32

vlad's user avatar

The reason I was facing this was because I had two «models.py» files which contained slightly different fields.
I resolved it by:

  1. deleting one of the models.py files
  2. correcting references to the deleted file
  3. then running manage.py syncdb

answered Nov 11, 2013 at 7:02

Amey's user avatar

I got this issue after copying mytable.idb table file from another location. To fix this problem I did the following:

ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;

Copy mytable.idb

ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;

Restart MySql

answered Apr 13, 2014 at 20:34

l0pan's user avatar

l0panl0pan

4667 silver badges11 bronze badges

1

I had the same issue. It happened after windows start up error, it seems some files got corrupted due to this. I did import the DB again from the saved script and it works fine.

answered Oct 31, 2014 at 22:51

Ayman Al-Absi's user avatar

I had this problem because of a trigger not working..Worked after I deleted the trigger.

answered Aug 2, 2016 at 12:21

DauleDK's user avatar

DauleDKDauleDK

3,19310 gold badges54 silver badges95 bronze badges

In my case, MySQL’s parameter; lower_case_table_names was configured = 0.

It causes queries related with using upper cases will not work.

answered Aug 9, 2017 at 6:25

hiropon's user avatar

hiroponhiropon

1,6452 gold badges18 silver badges41 bronze badges

For me it was a table name upper/lower case issue. I had to make sure that table case name matched in a delete query, table notifications was not the same as Notifications. I fixed it by matching table name case with query and what MySQLWorkbench reported.

What is wierd is that this error showed up in a worked sql statement. Don’t know what caused this case sensitivity. Perhaps an auto AWS RDS update.

answered Mar 16, 2018 at 15:43

Kahitarich's user avatar

KahitarichKahitarich

3852 silver badges7 bronze badges

if you are modifying mysql bin->data dir’s and after that, your database import will not works

so you need to close wamp and after that start wamp

now database import will work fine

answered Jan 15, 2021 at 19:03

Hassan Saeed's user avatar

Hassan SaeedHassan Saeed

6,2111 gold badge37 silver badges37 bronze badges

Make sure you do not have a trigger that is trying to do something with the table mentioned in the error. I was receiving Error Code: 1146. Table 'exampledb.sys_diagnotics' doesn't exist on insert queries to another table in my production database. I exported the table schemas of my production database then searched for instances of exampledb.sys_diagnotics the schema SQL and found a debugging insert statement I had added to a table trigger in my development environment but this debug statement had been copied to production. The exampledb.sys_diagnotics table was not present on my production database. The error was resolved by removing the debug statement in my table trigger.

answered May 4, 2022 at 19:33

w. Patrick Gale's user avatar

In our role as Support Engineers for web hosts, we manage servers with various services such as web, database, mail, control panels, FTP, etc.

MySQL is the most commonly used database server in Linux hosting and handling the databases and resolving the errors associated with it, is a common task that we perform.

A commonly noticed error in MySQL server is ‘1146 table doesn’t exist’. Today we’ll see what causes this ‘1146 table doesn’t exist’ error in MySQL and how to fix it.

Error : Table ‘mysql.innodb_index_stats’ doesn’t exist
status : Operation failed

What causes MySQL ‘1146 table doesn’t exist’ error

MySQL table errors happen due to many reasons, the major ones we’ve come across include:

  1. InnoDB crash – When the InnoDB server crash due to any process load or user abuse, or if the server was not restarted properly, it can get corrupt and cause table errors to show up.
  2. Missing ibdata file in the MySQL datadir – InnoDB has a data dictionary – the ibdata file and log files, which are crucial for InnoDB to function. If during migrations or restorations, these files go missing, it can prevent InnoDB tables from functioning right.
  3. Improperly placed .frm files – In InnoDB, tables have ‘.frm’ files that define the table format. If these files get deleted or were missed to copy over to the proper database directory, then the tables can show errors.
  4. Incorrect permissions and ownership of MySQL datadir – MySQL has a data directory, usually ‘/var/lib/mysql’ that stores the databases. If the permission and ownership of this directory is not adequate for MySQL to access it, errors would occur.
  5. Corrupt tables or improper table names – If the database tables got corrupt due to improper server shut down or incomplete queries, or if the table name format is not correct, the ‘1146 table doesn’t exist’ error may show up.

[ You don’t have to lose your sleep over server errors. Our expert server support specialists monitor & maintain your servers 24/7/365 and keep them rock solid. ]

How to fix MySQL ‘1146 table doesn’t exist’ error

Inorder to fix the error ‘1146 table doesn’t exist’, we adopt different techniques, after analyzing the root cause of the error.

  1. Restart MySQL server – If the error has happened due to improper server shut down or MySQL service related errors, we restart the service and check if it fixes the issue. If the service doesn’t start properly, we further investigate and fix the error.
  2. Repair the tables – MySQL has tools such as ‘myisamchk’ to repair corrupt databases and tables.  
  3. Backup restore – Restoring database backups is the final resort to get the tables back to working condition. We always configure and maintain the backups in our customers’ servers up to date, inorder to ensure that there is no data loss or down time due to unexpected crashes or errors.
  4. Copy ibdata file – If the ‘ibdata’ file is missing, we copy it from the backup and restore it to the data directory for MySQL, after discarding the tablespace to avoid any corruptions or errors.
  5. InnoDB crash recovery – In case where the backup is incomplete or ibdata file is also corrupt, we’ve still been able to recover the tables via our expert crash recovery methods. Read the post ‘Database crash rescue‘ to know more.

[ Use your time to build your business. We’ll take care of your servers. Hire Our server experts to resolve and prevent server issues. ]

At Bobcares, our 24/7 Web Support Specialists constantly monitor all the services in the server and proactively audit the server for any errors or corruption in them.

With our systematic debugging approach for service or other software errors, we have been able to provide an exciting support experience to the customers.

If you would like to know how to avoid downtime for your customers due to errors or other service failures, we would be happy to talk to you.

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Summary: This article provides the user with a comprehensive solution to a query like “MySQL error 1146 table does not exist” using manual and professional (MySQL Database Recovery) methods. Follow each of the steps discussed here to resolve MySQL ‘1146 The table does not exist errors in your SQL Server. Download Now   Purchase Now

MySQL database is a relational database system that contains tables, these tables are formally described and they contain data within them. The data could be accessed and modified in various ways and there is no need for changing the order of tables for it. Pretty cool, Isn’t it? But sometimes corruption or mishandling of the data can lead us to errors. Error 1146 in MySQL Table doesn’t exist is also one of those common errors which can take place during MySQL handling.

So, in this handout, I’ll elaborate MySQL Error 1146, the reason behind this error and how to resolve Bug? #1146 – Table ‘xxx.xxxxx’ doesn’t exist. So without wasting time, let’s get started.

Why Error 1146 in MySQL Takes Place?

There are multiple reasons and catalyst to this error. Some of the causes to error 1146 are stated below:

  • InnoDB crash and missing data files

As we all know that InnoDB is the transaction-safe (ACID compliant) storage engine for MySQL database, it offers multiple capabilities like Rollback, Commit and crash recovery for data of MySQL database. The InnoDB is also prone to corruption, so if it is not handled correctly there is a chance of crash of InnoDB. InnoDB is functional because of ibdata file and log file. It acts as a data dictionary to it. If by any reason these files go missing, there will be no chance of working InnoDB and MySQL will show you error 1146.

  • Improper directory accessing permissions

MySQL has a data storage directory where it stores all the database. Most of the time path is ‘/var/lib/mysql’. If the ownership and access permissions are not right and MySQL is not able to access this directory path then the error 1146 in MySQL will be shown.

  • Corruption in data tables

Tables of MySQL database can get corrupt due to several reasons like improper server shutdown, incomplete queries, user abuse, wrong formats, foreign key constraint error, etc. So if the table got corrupt the database can show MySQL error 1146.

  • .frm file missing 

.frm file contains the format and structure of the database. If anyhow this file is not copied to the database directory or it gets deleted then there will be an error message for error code 1146.

Methods to Fix MySQL ERROR 1146 table doesn’t exist

To fix Bug? #1146 – Table ‘xxx.xxxxx’ doesn’t exist, we can use multiple remedies and DIYs like:

Restore Backup

This is the best alternative you should use. It will surely recreate all the lost tables from the database and MySQL code 1146 will also get solved but keep in mind that there should be a backup file to restore. So always keep the habit of creating backup time to time, it’s a good practice. Also, it resolve MySQL ERROR 1146 table doesn’t exist after backup.

Restart the Server

Try to restart the server if any improper server shutdown took place. There is a chance to get it back in working condition and removing error code. So that user access MySQL without any issue

Repair Database Tables

You can repair database tables using MySQL CLI. All you need to do is to follow the stated steps:

1. Using SSH, log in to the server.

2. From the command line, execute the following command:

             mysql -u [username] -p

             Note: Replace username with your username and remove the brackets.

3. Now enter your password for the username.

4. Again enter the command:

             use [databasename];

             Note: provide the name of the database without brackets.

5. Now execute the following command:

             show tables;

6. Now repair table using following commands:

             (a) Check for tables with error:

                    check table [tablename];

             (b) Repair tables:

                    repair table [tablename];

7. Now quit using quit command.

Keep a copy of .frm file

You can keep a copy of .frm file and whenever the error 1146 arrises, you can paste the .frm file to the schema folder. It can fix error 1146.

Copy the ibdata file from backup

You should keep a copy of ibdata file as a backup so whenever the this MySQL error takes place you can paste it to the data directory of MySQL server.

Resolve MySQL ERROR 1146 table doesn’t exist using Professional Methods

If still, the error 1146 in MySQL takes place, you should go for a professional tool rather relying on the DIYs. You can use MySQL Data Recovery tool. It is the best tool to recover the corrupt tables and even fix MySQL ERROR 1146 table doesn’t exist after backup.

Watch this video tutorial for smooth use of MySQL Recovery Tool.

Conclusion

So, this is Error 1146 in MySQL ‘table doesn’t exist’. We discussed some quick remedies and DIYs to resolve this common MySQL error. It becomes really hard and disappointing when you face such errors cause these types of errors can lead you to lose all your valuable data.

Try your best and keeping the backup of data is the best precaution you can take. It will help you in such a critical situation to restore your MySQL database in the previous condition and it will also fix Bug? #1146 – Table ‘xxx.xxxxx’ doesn’t exist. So hope for the best and do it. Thanks fo reading this article. I hope you found it useful & interesting.

Related Post

I changed the datadir of a MySQL installation and all the bases moved correctly except for one.
I can connect and USE the database. SHOW TABLES also returns me all the tables correctly, and the files of each table exists on the MySQL data directory.

However, when I try to SELECT something from the table, I get an error message that the table does not exist. Yet, this does not make sense since I was able to show the same table through SHOW TABLES statement.

My guess is that SHOW TABLES lists file existence but does not check whether a file is corrupted or not. Consequently, I can list those files but not access them.

Nevertheless, it is merely a guess. I have never seen this before. Now, I cannot restart the database for testing, but every other application that uses it is running fine.
But that’s just a guess, I’ve never seen this before.

Does anyone know why this is happening?

Example:

mysql> SHOW TABLES;
+-----------------------+
| Tables_in_database    |
+-----------------------+
| TABLE_ONE             |
| TABLE_TWO             |
| TABLE_THREE           |
+-----------------------+
mysql> SELECT * FROM TABLE_ONE;
ERROR 1146 (42S02): Table 'database.TABLE_ONE' doesn't exist

SK98's user avatar

asked Oct 13, 2011 at 19:07

johnsmith's user avatar

13

Just in case anyone still cares:

I had the same issue after copying a database directory directly using command

cp -r /path/to/my/database /var/lib/mysql/new_database

If you do this with a database that uses InnoDB tables, you will get this crazy ‘table does not exist’ error mentioned above.

The issue is that you need the ib* files in the root of the MySQL datadir (e.g. ibdata1, ib_logfile0 and ib_logfile1).

When I copied those it worked for me.

the's user avatar

the

20.8k11 gold badges68 silver badges101 bronze badges

answered Jul 27, 2012 at 21:46

Mike Dacre's user avatar

Mike DacreMike Dacre

2,9051 gold badge12 silver badges2 bronze badges

23

For me on Mac OS (MySQL DMG Installation) a simple restart of the MySQL server solved the problem. I am guessing the hibernation caused it.

the's user avatar

the

20.8k11 gold badges68 silver badges101 bronze badges

answered Feb 12, 2014 at 12:38

Martin's user avatar

MartinMartin

6216 silver badges7 bronze badges

5

I get this issue when the case for the table name I’m using is off. So table is called ‘db’ but I used ‘DB’ in select statement. Make sure the case is the same.

answered Oct 13, 2011 at 19:13

dkinzer's user avatar

dkinzerdkinzer

31.9k12 gold badges66 silver badges85 bronze badges

1

This error can also occur when setting lower_case_table_names to 1, and then trying to access tables that were created with the default value for that variable. In that case you can revert it to the previous value and you will be able to read the table.

answered Jun 17, 2014 at 12:18

golimar's user avatar

golimargolimar

2,3891 gold badge22 silver badges33 bronze badges

2

I don’t know the reason but in my case I solved just disabling and enabling the foreign keys check

SET FOREIGN_KEY_CHECKS=0;
SET FOREIGN_KEY_CHECKS=1;

answered Jun 29, 2016 at 14:34

Bruno Caponi's user avatar

4

  1. stop mysqld
  2. backup mysql folder: cp -a /var/lib/mysql /var/lib/mysql-backup
  3. copy database folder from old machine to /var/lib/mysql
  4. override ib* (ib_logfile* , ibdata ) from old database
  5. start mysqld
  6. dump dabase
  7. mysqldump >dbase.mysql
  8. stop mysql service
  9. remove /var/lib/mysql
  10. rename /var/lib/mysql-backup to /var/lib/mysql
  11. start mysqld
  12. create the database
  13. mysqldump < dbase.mysql

Djizeus's user avatar

Djizeus

4,1611 gold badge23 silver badges42 bronze badges

answered Dec 3, 2012 at 0:51

user1772382's user avatar

user1772382user1772382

5366 silver badges5 bronze badges

4

Please run the query:

SELECT 
    i.TABLE_NAME AS table_name, 
    LENGTH(i.TABLE_NAME) AS table_name_length,
    IF(i.TABLE_NAME RLIKE '^[A-Za-z0-9_]+$','YES','NO') AS table_name_is_ascii
FROM
    information_schema.`TABLES` i
WHERE
    i.TABLE_SCHEMA = 'database'

Unfortunately MySQL allows unicode and non-printable characters to be used in table name.
If you created your tables by copying create code from some document/website, there is a chance that it has zero-width-space somewhere.

answered Oct 13, 2011 at 19:58

dev-null-dweller's user avatar

dev-null-dwellerdev-null-dweller

29.2k3 gold badges65 silver badges85 bronze badges

1

I had the same problem and I searched for 2-3 days, but the solution for me was really stupid.

Restart the mysql

$ sudo service mysql restart

Now tables become accessible.

answered Feb 25, 2017 at 7:55

Siraj Alam's user avatar

Siraj AlamSiraj Alam

9,0189 gold badges52 silver badges64 bronze badges

2

I have just spend three days on this nightmare. Ideally, you should have a backup that you can restore, then simply drop the damaged table. These sorts of errors can cause your ibdata1 to grow huge (100GB+ in size for modest tables)

If you don’t have a recent backup, such as if you relied on mySqlDump, then your backups probably silently broke at some point in the past. You will need to export the databases, which of course you cant do, because you will get lock errors while running mySqlDump.

So, as a workaround, go to /var/log/mysql/database_name/ and remove the table_name.*

Then immediately try to dump the table; doing this should now work. Now restore the database to a new database and rebuild the missing table(s). Then dump the broken database.

In our case we were also constantly getting mysql has gone away messages at random intervals on all databases; once the damaged database were removed everything went back to normal.

Krythic's user avatar

Krythic

4,1245 gold badges26 silver badges67 bronze badges

answered Nov 28, 2012 at 12:50

Andy's user avatar

AndyAndy

3782 silver badges8 bronze badges

3

Try to run sql query to discard tablespace before copying idb-file:

ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;

Copy idb-file

ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;

Restart MySql

reformed's user avatar

reformed

4,45011 gold badges60 silver badges87 bronze badges

answered Apr 13, 2014 at 20:39

l0pan's user avatar

l0panl0pan

4667 silver badges11 bronze badges

2

O.k. this is going to sound pretty absurd, but humor me.
For me the problem got resolved when I changed my statement to this :

SELECT * FROM `table`

I made two changes
1.) Made the table name lower case — I know !!
2.) Used the specific quote symbol = ` : It’s the key above your TAB

The solution does sound absurd, but it worked and it’s Saturday evening and I’ve been working since 9 a.m. — So I’ll take it :)

Good luck.

answered Dec 13, 2014 at 22:55

PlanetUnknown's user avatar

PlanetUnknownPlanetUnknown

3,9564 gold badges48 silver badges66 bronze badges

3

What worked for me, was just dropping the table, even though it didnt exist. Then I re created the table and repopulated from an sql dump done previously.

There must be some metabase of table names, and it was most likely still existing in there till i dropped it.

answered Nov 19, 2013 at 17:39

Zoobra McFly's user avatar

1

Had a similar problem with a ghost table. Thankfully had an SQL dump from before the failure.

In my case, I had to:

  1. Stop mySQL
  2. Move ib* files from /var/mysql off to a backup
  3. Delete /var/mysql/{dbname}
  4. Restart mySQL
  5. Recreate empty database
  6. Restore dump file

NOTE: Requires dump file.

bjb568's user avatar

bjb568

11k11 gold badges50 silver badges71 bronze badges

answered Jan 5, 2013 at 16:45

Oli Stockman's user avatar

2

I had this problem after upgrading WAMP but having no database backup.

This worked for me:

  1. Stop new WAMP

  2. Copy over database directories you need and ibdata1 file from old WAMP installation

  3. Delete ib_logfile0 and ib_logfile1

  4. Start WAMP

You should now be able to make backups of your databases. However after your server restarts again you will still have problems. So now reinstall WAMP and import your databases.

Rohan Khude's user avatar

Rohan Khude

4,3455 gold badges49 silver badges44 bronze badges

answered Jun 8, 2016 at 15:10

ykay says Reinstate Monica's user avatar

3

After having to reinstall MySQL I had this same problem, it seems that during the install, some configuration files that store data about the InnoDB log files, these files ib_logfile* (they are log files right?), are overwriten. To solve this problem I just deleted the ib_logfile* files.

answered Sep 5, 2012 at 22:21

jonathancardoso's user avatar

jonathancardosojonathancardoso

11.6k7 gold badges53 silver badges72 bronze badges

1

  1. Do mysqldump to database:

    mysqldump -u user -ppass dbname > D:Back-upsdbname.sql
    
  2. Restore database

    mysql -u user -ppass dbname < D:Back-upsdbname.sql
    

Now all tables in database were restored completely. Try..

SELECT * FROM dbname.tablename;

Stephen Rauch's user avatar

Stephen Rauch

47.4k31 gold badges105 silver badges134 bronze badges

answered Jan 18, 2018 at 1:42

Zaw Htoon's user avatar

Zaw HtoonZaw Htoon

591 silver badge5 bronze badges

It appears that the issue has to do (at least in mine and a few others) with invalid (corrupt?) innodb log files. Generally speaking, they simply need to be recreated.

Here are solutions, most of which require a restart of mysql.

  • Recreate your log files (Delete and restart mysql)
  • Resize your log files (MySql 5.6+ will regenerate the file for you)
  • If you are doing some type of a data migration, make sure you have correctly migrated the right file and given it permissions as others have already stated
  • Check permissions of your data and log files, that mysql is owner of both
  • If all else fails, you will likely have to recreate the database

Community's user avatar

answered Jul 17, 2014 at 16:22

SeanDowney's user avatar

SeanDowneySeanDowney

17.3k20 gold badges81 silver badges90 bronze badges

1

In my case, i had defined a trigger on the table and then was trying to insert the row in table. seems like, somehow trigger was erroneous, and hence insert was giving error, table doesn’t exist.

answered Dec 31, 2017 at 6:26

Yogesh Kumar Gupta's user avatar

1

Copy only ibdata1 file from your old data directory. Do not copy ib_logfile1 or ib_logfile0 files. That will cause MySQL to not start anymore.

answered Feb 18, 2018 at 7:02

Plabon Dutta's user avatar

Plabon DuttaPlabon Dutta

6,7293 gold badges29 silver badges33 bronze badges

1

Came cross same problem today. This is a mysql «Identifier Case Sensitivity» issue.

Please check corresponding data file. It is very likely that file name is in lower case on file system but table name listed in «show tables» command is in upper case. If system variable «lower_case_table_names» is 0, the query will return «table not exist» because name comparisons are case sensitive when «lower_case_table_names» is 0.

answered Apr 10, 2018 at 10:19

Hudson Liang's user avatar

Its possible you have a hidden character in your table name. Those don’t show up when you do a show tables. Can you do a «SHOW CREATE TABLE TABLE_ONE» and tab complete the «TABLE_ONE» and see if it puts in any hidden characters. Also, have you tried dropping and remaking the tables. Just to make sure nothing is wrong with the privileges and that there are no hidden characters.

answered Oct 13, 2011 at 19:57

Hoopdady's user avatar

HoopdadyHoopdady

2,2763 gold badges25 silver badges40 bronze badges

1

I installed MariaDB on new computer,
stopped Mysql service
renamed data folder to data-
I solved my problem copying just
Mysqldatatable_folders and ibdata1
from crashed HD MySql data Folder to the new installed mysql data folder.

I Skipped ib_logfile0 and ib_logfile1 (otherwise the server did not start service)

Started mysql service.

Then server is running.

answered Mar 10, 2014 at 13:34

Tony's user avatar

TonyTony

16.3k15 gold badges78 silver badges132 bronze badges

1

Same exact problem after TimeMachine backup import. My solution was to stop the MySQL server and fix read-write permissions on the ib* files.

answered Mar 13, 2014 at 13:12

user3415481's user avatar

One other answer I think is worth bringing up here (because I came here with that same problem and this turned out to be the answer for me):

Double check that the table name in your query is spelled exactly the same as it is in the database.

Kind of an obvious, newbie thing, but things like «user» vs «users» can trip people up and I thought it would be a helpful answer to have in the list here. :)

answered Aug 13, 2014 at 18:57

vazor's user avatar

vazorvazor

1233 silver badges12 bronze badges

In my case, when I was importing the exported sql file, I was getting an error like table doesn’t exist for the create table query.

I realized that there was an underscore in my database name and mysql was putting an escape character just before that.

So I removed that underscore in the database name, everything worked out.

Hope it helps someone else too.

answered Jan 28, 2015 at 8:57

Onur Kucukkece's user avatar

Onur KucukkeceOnur Kucukkece

1,6981 gold badge20 silver badges46 bronze badges

Here is another scenario (version upgrade):

I reinstalled my OS (Mac OS El Captain) and installed a new version of mysql (using homebrew). The installed version (5.7) happened to be newer than my previous one. Then I copied over the tables, including the ib* files, and restarted the server. I could see the tables in mysql workbench but when I tried to select anything, I got «Table doesn’t exist».

Solution:

  1. stop the mysql server e.g. mysql.server stop or brew services stop mysql
  2. start the server using mysqld_safe --user=mysql --datadir=/usr/local/var/mysql/ (change path as needed)
  3. run mysql_upgrade -u root -p password (in another terminal window)
  4. shut down the running server mysqladmin -u root -p password shutdown
  5. restart the server in normal mode mysql.server start or brew services start mysql

Relevant docs are here.

answered May 31, 2016 at 23:34

Roman Kutlak's user avatar

Roman KutlakRoman Kutlak

2,6741 gold badge19 silver badges24 bronze badges

1

My table had somehow been renamed to ' Customers' i.e. with a leading space

This meant

a) queries broke

b) the table didn’t appear where expected in the alphabetical order of my tables, which in my panic meant I couldn’t see it!

RENAME TABLE ` Customer` TO `Customer`;

answered Aug 26, 2016 at 12:55

zzapper's user avatar

zzapperzzapper

4,6835 gold badges48 silver badges45 bronze badges

In my case it was SQLCA.DBParm parameter.

I used

SQLCA.DBParm = "Databse = "sle_database.text""

but it must be

SQLCA.DBParm = "Database='" +sle_database.text+ "'"

Explaination :

You are going to combine three strings :

 1. Database='              -  "Database='"

 2. (name of the database)  - +sle_database.text+

 3. '                       - "'" (means " ' "  without space)

Don’t use spaces in quatermarks.
Thank to my colleague Jan.

Rohìt Jíndal's user avatar

Rohìt Jíndal

25.3k12 gold badges70 silver badges123 bronze badges

answered Apr 3, 2013 at 13:13

Marek's user avatar

MarekMarek

111 bronze badge

Go to :xamppmysqldatadbname
inside dbname have tablename.frm and tablename.ibd file.
remove it
and restart mysql and try again.

answered Jun 14, 2017 at 8:40

Abu Sufian's user avatar

Abu SufianAbu Sufian

4395 silver badges8 bronze badges

I had the same issue in windows.
In addition to copying the ib* files and the mysql directory under thd data directory, I also had to match the my.ini file.

The my.ini file from my previous installation did not have the following line:

innodb-page-size=65536

But my new installation did. Possibly because I did not have that option in the older installer.
I removed this and restarted the service and the tables worked as expected.
In short, make sure that the new my.ini file is a replica of the old one, with the only exception being the datadir, the plugin-dir and the port#, depending upon your new installation.

answered Dec 22, 2019 at 21:02

Thennan's user avatar

ThennanThennan

7685 silver badges13 bronze badges

In our role as Support Engineers for web hosts, we manage servers with various services such as web, database, mail, control panels, FTP, etc.

MySQL is the most commonly used database server in Linux hosting and handling the databases and resolving the errors associated with it, is a common task that we perform.

A commonly noticed error in MySQL server is ‘1146 table doesn’t exist’. Today we’ll see what causes this ‘1146 table doesn’t exist’ error in MySQL and how to fix it.

Error : Table ‘mysql.innodb_index_stats’ doesn’t exist
status : Operation failed

What causes MySQL ‘1146 table doesn’t exist’ error

MySQL table errors happen due to many reasons, the major ones we’ve come across include:

  1. InnoDB crash – When the InnoDB server crash due to any process load or user abuse, or if the server was not restarted properly, it can get corrupt and cause table errors to show up.
  2. Missing ibdata file in the MySQL datadir – InnoDB has a data dictionary – the ibdata file and log files, which are crucial for InnoDB to function. If during migrations or restorations, these files go missing, it can prevent InnoDB tables from functioning right.
  3. Improperly placed .frm files – In InnoDB, tables have ‘.frm’ files that define the table format. If these files get deleted or were missed to copy over to the proper database directory, then the tables can show errors.
  4. Incorrect permissions and ownership of MySQL datadir – MySQL has a data directory, usually ‘/var/lib/mysql’ that stores the databases. If the permission and ownership of this directory is not adequate for MySQL to access it, errors would occur.
  5. Corrupt tables or improper table names – If the database tables got corrupt due to improper server shut down or incomplete queries, or if the table name format is not correct, the ‘1146 table doesn’t exist’ error may show up.

[ You don’t have to lose your sleep over server errors. Our expert server support specialists monitor & maintain your servers 24/7/365 and keep them rock solid. ]

How to fix MySQL ‘1146 table doesn’t exist’ error

Inorder to fix the error ‘1146 table doesn’t exist’, we adopt different techniques, after analyzing the root cause of the error.

  1. Restart MySQL server – If the error has happened due to improper server shut down or MySQL service related errors, we restart the service and check if it fixes the issue. If the service doesn’t start properly, we further investigate and fix the error.
  2. Repair the tables – MySQL has tools such as ‘myisamchk’ to repair corrupt databases and tables.  
  3. Backup restore – Restoring database backups is the final resort to get the tables back to working condition. We always configure and maintain the backups in our customers’ servers up to date, inorder to ensure that there is no data loss or down time due to unexpected crashes or errors.
  4. Copy ibdata file – If the ‘ibdata’ file is missing, we copy it from the backup and restore it to the data directory for MySQL, after discarding the tablespace to avoid any corruptions or errors.
  5. InnoDB crash recovery – In case where the backup is incomplete or ibdata file is also corrupt, we’ve still been able to recover the tables via our expert crash recovery methods. Read the post ‘Database crash rescue‘ to know more.

[ Use your time to build your business. We’ll take care of your servers. Hire Our server experts to resolve and prevent server issues. ]

At Bobcares, our 24/7 Web Support Specialists constantly monitor all the services in the server and proactively audit the server for any errors or corruption in them.

With our systematic debugging approach for service or other software errors, we have been able to provide an exciting support experience to the customers.

If you would like to know how to avoid downtime for your customers due to errors or other service failures, we would be happy to talk to you.

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

I am using windows XP. I am creating a table in phpMyAdmin using its built-in create table feature,
my database name is ddd.

It generates the following code:

CREATE TABLE  `ddd`.`mwrevision` (

`asd` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`sddd` INT NOT NULL
) ENGINE = INNODB;

and the following error shows up:

MySQL said:     
#1146 - Table 'ddd.mwrevision' doesn't exist 

What might be the problem?

mins's user avatar

mins

5,84411 gold badges52 silver badges72 bronze badges

asked Jun 14, 2011 at 10:29

Shaheer's user avatar

9

I also had same problem in past. All had happend after moving database files to new location and after updating mysql server. All tables with InnoDB engine disappeared from my database. I was trying to recreate them, but mysql told me 1146: Table 'xxx' doesn't exist all the time until I had recreated my database and restarted mysql service.

I think there’s a need to read about InnoDB table binaries.

Rafael Barros's user avatar

answered Dec 7, 2011 at 4:43

sempasha's user avatar

sempashasempasha

6235 silver badges18 bronze badges

2

I had the same problem and can’t get a good tip for this over the web, so I shared this for you and for all who needs.

In my situation I copy a database (all files: frm, myd) to the data folder in MySQL data folder (using Wamp at home). All thing was OK until I want to create a table and have the error #1146 Table '...' doesn't exist!.

I use Wamp 2.1 with MySQL version 5.5.16.

My solution:

  1. Export the database to file;

  2. verify if exported file is really OK!!;

  3. drop the database where I have issues;

  4. create a new database with the same name that the last;

  5. import the file to the database.

FOR ME IS PROBLEM SOLVED. Now I can create tables again without errors.

Rafael Barros's user avatar

answered Jan 24, 2012 at 6:30

carlos's user avatar

carloscarlos

1111 silver badge2 bronze badges

1

Restarting MySQL works fine for me.

answered Nov 2, 2014 at 18:24

Muhammad Usman's user avatar

Muhammad UsmanMuhammad Usman

10.2k22 gold badges71 silver badges107 bronze badges

0

In my case I ran this command even if the table wasn’t visible in PhpMyAdmin :

DROP TABLE mytable

then

CREATE TABLE....

Worked for me !

answered May 21, 2015 at 9:22

Jim 007's user avatar

Jim 007Jim 007

2201 gold badge3 silver badges8 bronze badges

1

Check filenames.

You might need to create a new database in phpmyadmin that matches the database you’re trying to import.

Mayur Birari's user avatar

Mayur Birari

5,8278 gold badges33 silver badges61 bronze badges

answered Nov 21, 2012 at 15:23

blarg's user avatar

blargblarg

3,72310 gold badges40 silver badges69 bronze badges

2

I had the same problem. I tried to create a table in mysql and got the same error. I restarted mysql server and ran the command and was able to create/migrate table after restating.

answered May 10, 2013 at 11:10

thekosmix's user avatar

thekosmixthekosmix

1,68521 silver badges33 bronze badges

Today i was facing same problem. I was in very difficult situation but what id did i create a table with diffrent name e.g (modulemaster was not creating then i create modulemaster1) and after creating table i just do the rename table.

answered Jun 12, 2013 at 11:57

Vipin Gurjar's user avatar

I encountered the same problem today. I was trying to create a table users, and was prompted that ERROR 1146 (42S02): Table users doesn't exist, which did not make any sense, because I was just trying to create the table!!

I then tried to drop the table by typing DROP TABLE users, knowing it would fail because it did not exist, and I got an error, saying Unknown table users. After getting this error, I tried to create the table again, and magically, it successfully created the table!

My intuition is that I probably created this table before and it was not completely cleared somehow. By explicitly saying DROP TABLE I managed to reset the internal state somehow? But that is just my guess.

In short, try DROP whatever table you are creating, and CREATE it again.

answered Apr 6, 2015 at 17:51

Xin's user avatar

XinXin

4,2024 gold badges18 silver badges15 bronze badges

As pprakash mentions above, copying the table.frm files AND the ibdata1 file was what worked for me.

In short:

  1. Shut your DB explorer client (e.g. Workbench).
  2. Stop the MySQL service (Windows host).
  3. Make a safe copy of virtually everything!
  4. Save a copy of the table file(s) (eg mytable.frm) to the schema data folder (e.g. MySQL Server/data/{yourschema}).
  5. Save a copy of the ibdata1 file to the data folder (i.e., MySQL Server/data).
  6. Restart the MySQL service.
  7. Check that the tables are now accessible, queryable, etc. in your DB explorer client.

After that, all was well. (Don’t forget to backup if you have success!)

Community's user avatar

answered Aug 17, 2016 at 23:46

SteveCinq's user avatar

SteveCinqSteveCinq

1,8901 gold badge16 silver badges22 bronze badges

Column names must be unique in the table. You cannot have two columns named asd in the same table.

answered Jun 14, 2011 at 10:32

Oswald's user avatar

OswaldOswald

30.9k3 gold badges43 silver badges68 bronze badges

8

run from CMD & %path%=set to mysql/bin

mysql_upgrade -u user -ppassword

answered Jun 14, 2011 at 11:04

Ravi Parekh's user avatar

Ravi ParekhRavi Parekh

4,9189 gold badges43 silver badges57 bronze badges

2

Recently I had same problem, but on Linux Server. Database was crashed, and I recovered it from backup, based on simply copying /var/lib/mysql/* (analog mysql DATA folder in wamp). After recovery I had to create new table and got mysql error #1146. I tried to restart mysql, and it said it could not start. I checked mysql logs, and found that mysql simply had no access rigths to its DB files. I checked owner info of /var/lib/mysql/*, and got 'myuser:myuser' (myuser is me). But it should be 'mysql:adm' (so is own developer machine), so I changed owner to ‘mysql:adm’. And after this mysql started normally, and I could create tables, or do any other operations.

So after moving database files or restoring from backups check access rigths for mysql.

Hope this helps…

thvwns's user avatar

thvwns

3,5383 gold badges43 silver badges57 bronze badges

answered Aug 23, 2013 at 8:32

vlad's user avatar

The reason I was facing this was because I had two «models.py» files which contained slightly different fields.
I resolved it by:

  1. deleting one of the models.py files
  2. correcting references to the deleted file
  3. then running manage.py syncdb

answered Nov 11, 2013 at 7:02

Amey's user avatar

I got this issue after copying mytable.idb table file from another location. To fix this problem I did the following:

ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;

Copy mytable.idb

ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;

Restart MySql

answered Apr 13, 2014 at 20:34

l0pan's user avatar

l0panl0pan

4667 silver badges11 bronze badges

1

I had the same issue. It happened after windows start up error, it seems some files got corrupted due to this. I did import the DB again from the saved script and it works fine.

answered Oct 31, 2014 at 22:51

Ayman Al-Absi's user avatar

I had this problem because of a trigger not working..Worked after I deleted the trigger.

answered Aug 2, 2016 at 12:21

DauleDK's user avatar

DauleDKDauleDK

2,9197 gold badges51 silver badges90 bronze badges

In my case, MySQL’s parameter; lower_case_table_names was configured = 0.

It causes queries related with using upper cases will not work.

answered Aug 9, 2017 at 6:25

hiropon's user avatar

hiroponhiropon

1,6152 gold badges18 silver badges41 bronze badges

For me it was a table name upper/lower case issue. I had to make sure that table case name matched in a delete query, table notifications was not the same as Notifications. I fixed it by matching table name case with query and what MySQLWorkbench reported.

What is wierd is that this error showed up in a worked sql statement. Don’t know what caused this case sensitivity. Perhaps an auto AWS RDS update.

answered Mar 16, 2018 at 15:43

Kahitarich's user avatar

KahitarichKahitarich

3652 silver badges7 bronze badges

if you are modifying mysql bin->data dir’s and after that, your database import will not works

so you need to close wamp and after that start wamp

now database import will work fine

answered Jan 15, 2021 at 19:03

Hassan Saeed's user avatar

Hassan SaeedHassan Saeed

5,7911 gold badge33 silver badges37 bronze badges

Make sure you do not have a trigger that is trying to do something with the table mentioned in the error. I was receiving Error Code: 1146. Table 'exampledb.sys_diagnotics' doesn't exist on insert queries to another table in my production database. I exported the table schemas of my production database then searched for instances of exampledb.sys_diagnotics the schema SQL and found a debugging insert statement I had added to a table trigger in my development environment but this debug statement had been copied to production. The exampledb.sys_diagnotics table was not present on my production database. The error was resolved by removing the debug statement in my table trigger.

answered May 4, 2022 at 19:33

w. Patrick Gale's user avatar

Last updated on July 22nd, 2021 at 11:16 am

MySQL database is a relational database system which contains tables, these tables are formally described and they contain data within them. The data could be accessed and modify with various ways and there is no need for changing the order of tables for it. Pretty cool, Isn’t it? But sometimes corruption or mishandling of the data can lead us to errors. Error 1146 in MySQL Table doesn’t exist is also one of those common errors which can take place during MySQL handling.

So, in this handout, I’ll elaborate MySQL Error 1146, the reason behind this error and how to resolve Bug? #1146 – Table ‘xxx.xxxxx’ doesn’t exist. So without wasting time, let’s get started.

Why Error 1146 in MySQL Takes Place?

There are multiple reasons and catalyst to this error. Some of the causes to error 1146 are stated below:

  • InnoDB crash and missing data files

As we all know that InnoDB is the transaction-safe (ACID compliant) storage engine for MySQL database, it offers multiple capabilities like Rollback, Commit and crash recovery for data of MySQL database. The InnoDB is also prone to corruption, so if it is not handled correctly there is a chance of crash of InnoDB. InnoDB is functional because of ibdata file and log file. It acts as a data dictionary to it. If by any reason these files go missing, there will be no chance of working InnoDB and MySQL will show you error 1146.

  • Improper directory accessing permissions

MySQL has a data storage directory where it stores all the database. Most of the time path is ‘/var/lib/mysql’. If the ownership and access permissions are not right and MySQL is not able to access this directory path then the error 1146 in MySQL will be shown.

  • Corruption in data tables

Tables of MySQL database can get corrupt due to several reasons like improper server shutdown, incomplete queries, user abuse, wrong formats, foreign key constraint error, etc. So if the table got corrupt the database can show MySQL error 1146.

  • .frm file missing 

.frm file contains the format and structure of the database. If anyhow this file is not copied to the database directory or it gets deleted then there will be an error message for error code 1146.

Methods to Fix MySQL ERROR 1146 table doesn’t exist

To fix Bug? #1146 – Table ‘xxx.xxxxx’ doesn’t exist, we can use multiple remedies and DIYs like:

Restore Backup

This is the best alternative you should use. It will surely recreate all the lost tables from the database and MySQL code 1146 will also get solved but keep in mind that there should be a backup file to restore. So always keep the habit of creating backup time to time, it’s a good practice. Also, it resolve MySQL ERROR 1146 table doesn’t exist after backup.

Restart the Server

Try to restart the server if any improper server shutdown took place. There is a chance to get it back in working condition and removing error code. So that user access MySQL without any issue

Repair Database Tables

You can repair database tables using MySQL CLI. All you need to do is to follow the stated steps:

1. Using SSH, log in to the server.

2. From the command line, execute the following command:

             mysql -u [username] -p

             Note: Replace username with your username and remove the brackets.

3. Now enter your password for the username.

4. Again enter the command:

             use [databasename];

             Note: provide the name of the database without brackets.

5. Now execute the following command:

             show tables;

6. Now repair table using following commands:

             (a) Check for tables with error:

                    check table [tablename];

             (b) Repair tables:

                    repair table [tablename];

7. Now quit using quit command.

Keep a copy of .frm file

You can keep a copy of .frm file and whenever the error 1146 arrises, you can paste the .frm file to the schema folder. It can fix error 1146.

Copy the ibdata file from backup

You should keep a copy of ibdata file as a backup so whenever the this MySQL error takes place you can paste it to the data directory of MySQL server.

Using Third Party Tools

If still, the error 1146 in MySQL takes place, you should go for a professional tool rather relying on the DIYs. You can use MySQL Data Recovery tool. It is the best tool to recover the corrupt tables and even fix MySQL ERROR 1146 table doesn’t exist after backup. Try the demo version of the solution from below button.

mysql recovery demo version download

Watch this video tutorial for smooth use of MySQL Recovery Tool.

Conclusion

So, this is Error 1146 in MySQL ‘table doesn’t exist’. We discussed some quick remedies and DIYs to resolve this common MySQL error. It becomes really hard and disappointing when you face such errors cause these type of errors can lead you to lose all your valuable data.

Try your best and keeping the backup of data is the best precaution you can take. It will help you in such a critical situation to restore your MySQL database in the previous condition and it will also fix Bug? #1146 – Table ‘xxx.xxxxx’ doesn’t exist. So hope for the best and do it. Thanks fo reading this article. I hope you found it useful & interesting.

Попытался сделать дамп (бэкап) БД через родную для MySQL утилиту mysqldump и получил ошибку:

Got error: 1146: Table `table_name` doesn't exist when using LOCK TABLES

Вместо table_name имя несуществующей таблицы. Т.е. сразу после введения в консоль/терминал команды:

mysqldump --user=root -p db_name > db_name.sql

получаю такую ошибку. Файл дампа создаётся, но он пустой, утилита mysqldump после выдачи этой ошибки перестаёт работать.

Попытки ухода от проблемы

Не стал обращать внимание на mysqldump и взял другие инструменты пытаясь убежать от проблемы, так сказать, решил применить альтернативные пути решения. Пробовал сделать дамп базы через менеджер баз данных phpMyAdmin и всё получилось, но при импорте (поднятии) дампа возникли ошибки. Так же пробовал сделать тамп через родной для MySQL графический менеджер БД MySQL Workbench, но он тоже стал ругаться и выдавать эту обишку ибо он так же пользуется утилитой командной строки mysqldump при экспорте БД. Пробовал экспортировать дамп БД так же при помощи Sypex Dumper, он сперва вроде работал, но потом тоже выдал аналогичную ошибку. Короче говоря зря я только тратил время с этими альтернативными инструментами работы с БД. Если не работает родной mysqldump, то и другие программы врядли помогут ибо с базой что-то не так и надо разбираться.

Попытки решения проблемы

Что же это за «doesn’t exist when using LOCK TABLES» такой. Придётся разобраться. Если перевести текст сообщения об ошибке, то в нём говорится примерно следующее: «Таблица `table_name` не существует при использовании команды LOCK TABLES». Т.е. не была найдена указанная таблица, что понятно, ведь её никто там не создавал и быть её не должно.

Если посмотреть базу через разные графические менеджеры БД вроде браузерного phpMyAdmin или десктопного MySQL Workbench, то такой таблицы в базе действительно нет и не должно быть, но СУБД MySQL почему-то считает, что она там есть или должна быть, однако если посмотреть базу через родной консольный менеджер БД mysql (MySQL monitor), то такая таблица там будет в общем списке таблиц. Надо разбираться.

Поискал ответы на свои вопросы в служебной таблице information_schema, но это ни к чему не привело. Сделал пакетную проверку и восстановление всех таблиц базы данных через родную утилиту mysqlcheck, но это не помогло. При проверке утилита так же нашла эту несуществующую таблицу и стала ругаться, что она не найдена, но работу доделала до конца:

Repairing tables
table_name
Error : Table 'table_name' doesn't exist
status : Operation failed

Решение проблемы

Воспользовался стандартным родным консольным менеджером БД, который так и называется mysql, он же полностью MySQL monitor. Зашёл под нужным пользователем БД, выбрал базу, вывел список таблиц базы и оказалось в этом списке действительно есть та самая несуществующая таблица, которая была указана в тексте сообщения об ошибке. Так же при попытке создать таблицу с таким именем получаешь сообщение об ошибке, что такая таблица уже существует. Решил посмотреть что же есть в этой таблице. Получил сообщение об ошибке, что такой таблицы не существует, что не удивительно, ведь её и не должно существовать, но СУБД MySQL считает, что она есть и выводит её в общем списке таблиц. Решил удалить эту таблицу и тоже получил сообщение, что такой таблицы нет и удалять нечего. После этого вновь запросил список всех таблиц базы данных и о чудо, это несуществующей таблицы в списке больше нет.

Таким образом, что бы решить проблему «Got error: 1146: Table `table_name` doesn’t exist when using LOCK TABLES» при работе с БД надо пользоваться родным консольным менеджером БД MySQL monitor (mysql). Попытайтесь сперва создать таблицу с таким именем и получите сообщеине об ошибке, что такая таблица уже есть в БД. Попытайтесь удалить эту таблицу и получите сообщение, что её и так нет. Во время одного из этих действий СУБД MySQL ещё раз проверит базу и убедится, что такой таблицы нет и вычеркнет её из мета информации БД, т.е. забудет про эту несуществующую таблицу, не будет выводить её в списке всех таблиц и не будет выводить эту ошикбу. Скорее всего проверка целостности базы происходит при попытке удаления этой несуществующей таблицы, поэтому пробовать создавать её и не нужно. Так же, возможно, пользоваться консольным MySQL monitor тоже не обязательно и можно послать SQL-запрос СУБД на удаление этой таблицы откуда удобно, просто в MySQL monitor эта таблица сперва отображается в общем списке а в остальных менеджерах баз данных не показывается. В общем точно не знаю что в моём алгоритме действий лишнее, а что необходимое, я лишь говорю как я решил эту проблему. Задача нетривиальная и попытаться воссоздать эту ошибку с целостностью базы ещё раз для учебных целей оказалось не просто. У меня был лишь один проход решения проблемы, поэтому, что точно её решило я не знаю.

Для тех кто всё ещё не понял, скажу кратко. Просто воспользуйетесь консольным MySQL monitor и через него попробуйте удалить эту несуществующую таблицу. При запросе удаления СУБД MySQL проверит базу, поймёт, что такой таблицы действительно нет и всё будет в порядке. Проблема решена, вот и всё.

На всякий случай прикладываю список консольных команд и SQL-запросов, которые я использовал в ходе решения этой проблемы. Хотел их писать сразу по ходу изложения, но решил, что это не нужно для тех кто и так знает, а для остальных (забывчивых) напишу список ниже, названия файлов, пользователей, таблиц и баз, естественно взяты для примера, подставляйте свои.

Для начала консольная команды.
Попытка сделать дамп базы через утилиту mysqldump:

mysqldump --user=root -p db_name > db_name.sql

Пакетная проверка и восстановление всех таблиц базы данных через родную утилиту mysqlcheck:

mysqlcheck --user=USER --password=PASSWORD --auto-repair --check --all-databases

Вход в консольный менеджер баз данных MySQL monitor с указанием данных:

mysql --user=USER --password=PASSWORD

Далее работает непосрдественно с БД, поэтому теперь пойдут SQL-запросы.
Просмотр всех доступных для пользователя (для просмотра) баз данных:

SHOW DATABASES;

Выбор необходимой рабочей базы данных для работы с ней:

USE <db_title>;

Просмотр всех доступных для пользователя таблиц выбранной базы данных:

SHOW TABLES;

Просмотр содержимого указанной таблицы (с лимитом записей/строк):

SELECT * FROM table_title LIMIT 100;

Удаление таблицы из базы данных:

DROP TABLE table_title;

Следует понимать, что несуществующая таблица, это ошибка структуры базы данных, т.е. надо копать в эту сторону, восстанавливать структуру БД, а не таблиц.

Если моё решение не помогло, то можно попробовать воспользоваться утилитой «innodb tools» (Percona Data Recovery Tool for InnoDB) (https://code.google(точка)com/archive/p/innodb-tools/). Ещё есть решение описанное здесь (http://adw0rd(точка)com/2009/07/02/recovery-innodb/), но там народ в комментариях говорит, что это не всегда помогает.

На этом все, всем спасибо за внимание.



Я использую windows XP. Я создаю таблицу в phpMyAdmin с помощью встроенной функции create table,
мое имя базы данных — ddd.

Он генерирует следующий код:

CREATE TABLE  `ddd`.`mwrevision` (

`asd` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`sddd` INT NOT NULL
) ENGINE = INNODB;

И появляется следующая ошибка:

MySQL said:     
#1146 - Table 'ddd.mwrevision' doesn't exist

В чем может быть проблема?


2398  


18  

18 ответов:

У меня тоже была такая же проблема в прошлом. Все произошло после перемещения файлов базы данных в новое место и после обновления сервера mysql. Все таблицы с движком InnoDB исчезли из моей базы данных. Я пытался воссоздать их, но mysql все время говорил мне 1146: Table 'xxx' doesn't exist, пока я не воссоздал свою базу данных и не перезапустил службу mysql.

Я думаю, что есть необходимость прочитать о двоичных файлах таблиц InnoDB.

У меня была та же проблема, и я не могу получить хороший совет для этого через интернет, поэтому я поделился этим для вас и для всех, кто нуждается.

В моей ситуации я копирую базу данных (все файлы: frm, myd) в папку данных в папке данных MySQL (используя Wamp дома). Все было в порядке, пока я не хочу создать таблицу и иметь ошибку #1146 Table '...' doesn't exist!.

Я использую Wamp 2.1 с MySQL версии 5.5.16.

Мое решение:

  1. Экспорт базы данных в файл;

  2. Проверьте, экспортируется ли файл действительно в порядке!!;

  3. Удалите базу данных, где у меня есть проблемы;

  4. Создайте новую базу данных с тем же именем, что и предыдущая;

  5. Импортируйте файл в базу данных.

ДЛЯ МЕНЯ ПРОБЛЕМА РЕШЕНА. Теперь я могу снова создавать таблицы без ошибок.

В моем случае я выполнил эту команду, даже если таблица не была видна в PhpMyAdmin:

DROP TABLE mytable

Затем

CREATE TABLE....

Работал на меня !

Перезапуск MySQL работает нормально для меня.

Проверьте имена файлов.

Возможно, вам потребуется создать новую базу данных в phpmyadmin, которая соответствует базе данных, которую вы пытаетесь импортировать.

У меня была та же проблема. Я попытался создать таблицу в mysql и получил ту же ошибку. Я перезапустил сервер mysql и запустил команду, и смог создать / перенести таблицу после пересчета.

Сегодня я столкнулся с той же проблемой. Я был в очень сложной ситуации, но какой id я создал таблицу с другим именем, например (modulemaster не создавал, тогда я создаю modulemaster1), и после создания таблицы я просто делаю переименование таблицы.

Я сегодня столкнулся с той же проблемой. Я пытался создать таблицу users, и мне было предложено это ERROR 1146 (42S02): Table users doesn't exist, что не имело никакого смысла, потому что я просто пытался создать таблицу!!

Затем я попытался отбросить таблицу, набрав DROP TABLE users, зная, что она не будет работать, потому что ее не существует, и я получил ошибку, сказав Unknown table users. После получения этой ошибки, я попытался создать таблицу снова, и волшебным образом, он успешно создал таблицу!

Моя интуиция подсказывает, что я, вероятно, создал это стол до этого так и не был полностью убран каким-то образом. Явно говоря DROP TABLE, мне удалось каким-то образом сбросить внутреннее состояние? Но это только мое предположение.

Короче говоря, попробуйте отбросить любую таблицу, которую вы создаете, и создать ее снова.

As pprakash упоминает выше, копируя таблицу .файлы frm и файл ibdata1 были тем, что работало для меня. (Я бы просто прокомментировал этот комментарий, но это требование SO для 50 пунктов означает, что я должен предоставить решение, даже если это просто повторение существующего … странный.)

Короче говоря:

  1. Закрой свой клиент проводнике выделенного текста(например, верстак).
  2. остановите службу MySQL (хост Windows).
  3. сделайте безопасную копию практически все!
  4. сохраните копию файла(ов) таблицы (например, mytable.frm ) в папку данных схемы (например, MySQL Server / data / {yourschema}).
  5. сохраните копию файла ibdata1 в папке data (т. е. MySQL Server/data).
  6. перезагрузите службу MySQL.
  7. убедитесь, что таблицы теперь доступны, доступны для запросов и т. д. В вашем клиенте проводника БД.

После этого все было хорошо. (Не забудьте сделать резервную копию, если у вас есть успех!)

Имена столбцов в таблице должны быть уникальными. В одной таблице не может быть двух столбцов с именем asd.

Выполнить из CMD & % path%=установить в mysql / bin

mysql_upgrade -u user -ppassword

Недавно у меня была такая же проблема, но на сервере Linux. База данных была разбита, и я восстановил ее из резервной копии, основанной на простом копировании /var/lib/mysql/* (аналоговая папка данных mysql в wamp). После восстановления я должен был создать новую таблицу и получил ошибку mysql #1146. Я попытался перезапустить mysql, и он сказал, что не может начать. Я проверил журналы mysql и обнаружил, что mysql просто не имел доступа к своим файлам DB. Я проверил информацию о владельце /var / lib / mysql/* и получил 'myuser:myuser' (мой пользователь-это я). Но он должен быть 'mysql:adm' (таков собственный машина разработчика), поэтому я сменил владельца на «mysql: adm». И после этого mysql начал нормально работать, и я мог создавать таблицы или делать любые другие операции.

Поэтому после перемещения файлов базы данных или восстановления из резервных копий проверьте доступ rigths для mysql.

Надеюсь, это поможет…

Причина, по которой я столкнулся с этим, заключалась в том, что у меня было два «models.py-файлы, которые содержали несколько иные поля.
Я решил ее следующим образом:

  1. удаление одного из models.py файлы
  2. исправление ссылок на удаленный файл
  3. затем запуск manage.py syncdb

Я получил эту проблему после копирования mytable.файл таблицы idb из другого места. Чтобы устранить эту проблему, я сделал следующее:

ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;

Скопируйте mytable.idb

ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;

Перезапустить MySql

У меня была та же проблема. Это произошло после ошибки запуска windows, кажется, некоторые файлы были повреждены из-за этого. Я снова импортировал БД из сохраненного скрипта, и он работает нормально.

У меня была эта проблема из-за того, что триггер не работал..Сработало после того, как я удалил триггер.

В моем случае параметр MySQL; lower_case_table_names был настроен = 0.

Это приводит к тому, что запросы, связанные с использованием верхних регистров, не будут работать.

Для меня это была проблема верхнего/нижнего регистра имени таблицы. Я должен был убедиться, что имя случая таблицы совпадает в запросе на удаление, таблица notifications не была такой же, как Notifications. Я исправил это, сопоставив имя таблицы case с запросом и тем, что сообщил MySQLWorkbench.

Что такое wierd, так это то, что эта ошибка появилась в рабочей инструкции sql. Не знаю, что вызвало такую чувствительность к делу. Возможно, автоматическое обновление AWS RDS.

18 ответов

У меня также была такая же проблема в прошлом. Все это произошло после перемещения файлов базы данных в новое место и после обновления сервера mysql. Все таблицы с движком InnoDB исчезли из моей базы данных. Я пытался их воссоздать, но mysql все время говорил мне 1146: Table 'xxx' doesn't exist, пока я не восстановил свою базу данных и не перезапустил службу mysql.

Мне кажется, что нужно читать бинарные файлы InnoDB.

sempasha
07 дек. 2011, в 04:49

Поделиться

У меня была такая же проблема и я не могу получить хороший совет для этого через Интернет, поэтому я поделился этим для вас и для всех, кто нуждается.

В моей ситуации я копирую базу данных (все файлы: frm, myd) в папку данных в папке данных MySQL (используя Wamp at home). Все было в порядке, пока я не хочу создать таблицу и имею ошибку #1146 Table '...' doesn't exist!.

Я использую Wamp 2.1 с MySQL версии 5.5.16.

Мое решение:

  • Экспорт базы данных в файл;

  • проверить, действительно ли экспортированный файл в порядке!

  • отбросить базу данных, где есть проблемы;

  • создать новую базу данных с тем же именем, что и последняя, ​​

  • импортируйте файл в базу данных.

ДЛЯ МЕНЯ РЕШЕНА ПРОБЛЕМА. Теперь я могу создавать таблицы снова без ошибок.

carlos
24 янв. 2012, в 07:12

Поделиться

В моем случае я выполнил эту команду, даже если таблица не была видна в PhpMyAdmin:

DROP TABLE mytable

затем

CREATE TABLE....

Работал для меня!

Jim 007
21 май 2015, в 10:56

Поделиться

Перезапуск MySQL отлично работает для меня.

Muhammad Usman
02 нояб. 2014, в 18:56

Поделиться

У меня была та же проблема. Я попытался создать таблицу в mysql и получил ту же ошибку. Я перезапустил сервер mysql и запустил команду и смог создать/перенести таблицу после повторения.

thekosmix
10 май 2013, в 12:19

Поделиться

Проверьте имена файлов.

Возможно, вам понадобится создать новую базу данных в phpmyadmin, которая соответствует базе данных, которую вы пытаетесь импортировать.

blarg
21 нояб. 2012, в 15:59

Поделиться

В качестве pprakash упоминается выше, копирование файлов table.frm И файл ibdata1 работал у меня. (Я бы просто прокомментировал этот комментарий, но это требование SO для 50 пунктов означает, что я должен предоставить решение, даже если это просто передел существующего… странный.)

Короче:

  • Закройте выделенный клиентом клиент-проводник DB (например, Workbench).
  • Остановить службу MySQL (хост Windows).
  • Сделайте безопасную копию практически всего!
  • Сохраните копию файлов таблиц (например, mytable.frm) в папку данных схемы (например, MySQL Server/data/{yourschema}).
  • Сохраните копию файла ibdata1 в папке с данными (например, MySQL Server/data).
  • Перезапустите службу MySQL.
  • Проверьте, что таблицы теперь доступны, доступны для запросов и т.д. в вашем клиенте проводника DB.

После этого все было хорошо. (Не забудьте сделать резервную копию, если у вас есть успех!)

SteveCinq
18 авг. 2016, в 01:05

Поделиться

Сегодня я столкнулся с той же проблемой. Я пытался создать таблицу users, и мне было предложено ERROR 1146 (42S02): Table users doesn't exist, что не имело никакого смысла, потому что я просто пытался создать таблицу!!

Затем я попытался удалить таблицу, набрав DROP TABLE users, зная, что она потерпит неудачу, потому что она не существует, и я получил сообщение об ошибке Unknown table users. Получив эту ошибку, я попытался снова создать таблицу, и, как ни странно, она успешно создала таблицу!

Моя интуиция заключается в том, что я, вероятно, создал эту таблицу раньше, и она каким-то образом не была полностью очищена. Явным образом сказал DROP TABLE мне удалось reset внутреннее состояние каким-то образом? Но это только моя догадка.

Короче говоря, попробуйте DROP любую таблицу, которую вы создаете, и СОЗДАЙТЕ ее снова.

Xin
06 апр. 2015, в 18:15

Поделиться

Сегодня я столкнулся с такой же проблемой. Я был в очень сложной ситуации, но какой идентификатор я создал таблицу с разным именем, например (modulemaster не создавал, затем я создавал modulemaster1), и после создания таблицы я просто делаю таблицу переименования.

Vipin Gurjar
12 июнь 2013, в 13:07

Поделиться

Для меня это была проблема с верхним/нижним регистром. Я должен был удостовериться, что имя файла таблицы совпало в запросе удаления, notifications таблицах были не такими же, как Notifications. Я исправил его, сопоставив случай с именем таблицы с запросом и сообщением MySQLWorkbench.

Что странно, так это то, что эта ошибка появилась в обработанном sql-заявлении. Не знаю, что вызвало чувствительность этого случая. Возможно, обновление AWS AWS.

Kahitarich
16 март 2018, в 17:40

Поделиться

В моем случае параметр MySQL; lower_case_table_names был настроен = 0.

Он вызывает запросы, связанные с использованием верхних регистров, не будет работать.

hiropon
09 авг. 2017, в 06:29

Поделиться

У меня была эта проблема из-за срабатывания триггера. Работала после того, как я удалил триггер.

DauleDK
02 авг. 2016, в 13:22

Поделиться

У меня была такая же проблема. Это произошло после ошибки запуска Windows, похоже, из-за этого некоторые файлы были повреждены. Я снова импортировал БД из сохраненного script, и он отлично работает.

Ayman Al-Absi
31 окт. 2014, в 23:38

Поделиться

Я получил эту проблему после копирования файла таблицы mytable.idb из другого места. Чтобы устранить эту проблему, я сделал следующее:

ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;

Скопировать файл mytable.idb

ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;

Перезагрузка MySql

l0pan
13 апр. 2014, в 21:57

Поделиться

Причина, по которой я столкнулся, состояла в том, что у меня было два файла «models.py», которые содержали несколько разных полей.
Я разрешил это:

  • удаление одного из файлов models.py
  • исправление ссылок на удаленный файл
  • затем запустите manage.py syncdb

Amey
11 нояб. 2013, в 07:31

Поделиться

Недавно у меня была такая же проблема, но на Linux Server. База данных была разбита, и я восстановил ее из резервной копии на основе простого копирования /var/lib/mysql/* (аналоговая папка DATA mysql в wamp). После восстановления мне пришлось создать новую таблицу и получить mysql-ошибку # 1146. Я попытался перезапустить mysql, и он сказал, что это не может начаться. Я проверил журналы mysql и обнаружил, что mysql просто не имеет доступа к своим файлам DB. Я проверил информацию о владельце /var/lib/mysql/ * и получил 'myuser:myuser' (myuser is me). Но это должно быть 'mysql:adm' (так это собственная машина разработчика), поэтому я сменил владельца на «mysql: adm». И после этого mysql начал нормально, и я мог создавать таблицы или выполнять любые другие операции.

Итак, после перемещения файлов базы данных или восстановления из резервных копий проверьте доступность буферов для mysql.

Надеюсь, что это поможет…

vlad
23 авг. 2013, в 09:53

Поделиться

запустить из CMD и% path% = установить в mysql/bin

mysql_upgrade -u user -ppassword

Ravi Parekh
14 июнь 2011, в 12:01

Поделиться

Имена столбцов должны быть уникальными в таблице. Вы не можете иметь два столбца с именем asd в той же таблице.

Oswald
14 июнь 2011, в 11:04

Поделиться

Ещё вопросы

  • 1СУММА на несколько отдельных столбцов в LINQ
  • 0Неустранимая ошибка PHP: класс ‘Vich UploaderBundle VichUploaderBundle’ не найден в / va r / app / current / app / AppKernel.php в строке 25
  • 0Обновите несколько записей с помощью mysql и nodeJs
  • 0Ember с загрузкой файла jquery
  • 0Div начинает прокрутку, когда заголовок достигает своей вершины, и прекращает прокрутку, когда его нижняя часть достигает нижнего колонтитула.
  • 1Java удалить ZipEntry
  • 0отображать событие в fullcalendar с пользовательскими данными на лету при изменении элемента ввода
  • 1Используйте Python OpenCV для обрезки / поворота / изменения размера игральных карт из изображения
  • 1Ошибка формы ввода с состоянием LSTM
  • 1Python Numpy добавить массив без выравнивания
  • 1EJBInvokerServlet / JMXInvokerServlet
  • 0Есть ли проблемы с производительностью, если моя таблица содержит более 200 столбцов в MySQL?
  • 1Оптимизация приложений Angular2
  • 1Скопируйте текст из JTextField в JTextArea
  • 0Форматирование аргументов в мыльных клиентах
  • 1Избегайте сбрасывать нули для запуска функции
  • 1Конвертировать и заказать временные метки
  • 0несколько запросов MySQL в одном массиве
  • 1Как добавить точки на Google Map в приложении для Android?
  • 0Создание случайного числа объектов
  • 1Пытаюсь обернуть мою голову * args в python [дубликаты]
  • 0Скопируйте конструктор для 2d массива с ++
  • 0Как получить массив идентификаторов из коллекции Doctrine во время сериализации
  • 1Крестики-нолики с минимаксным алгоритмом
  • 1ItemIndex DataLIst в asp.net
  • 0Как я могу получить первый элемент этого массива в этом объявлении var?
  • 1Android VideoView Проблема ландшафтной ориентации
  • 1Как исправить пропорции выхода
  • 1Преобразовать ‘Task <IList <T >>’ в ‘IList <T>’
  • 0MySQL вложенный запрос не работает с условием AND
  • 1Получить значение на основе фрейма данных индекса в Python
  • 0Подзапрос по формату базы данных Zend
  • 1Как назвать классы проекта для другого проекта?
  • 0AngularJS — Как изменить маршрут, только если что-то верно? [Дубликат]
  • 1Тройник и повторное соединение трубопроводов
  • 0Как полностью удалить границы таблицы для IE8
  • 1Внешний ввод в программу Python во время выполнения
  • 1Есть ли способ ввести переменную шага огурца из области действия сценария в cucmber?
  • 0Как использовать pagiantion в MySQL таблицы с Symfony и доктрины?
  • 0Почему проблема «Изменение ориентации изображения», которая захватывается с помощью камеры устройства и загружается на FTP-сервер, сохраняется в следующем сценарии?
  • 0Эффективность std :: tuple и std :: map
  • 0angularjs приращения повторения в условии if
  • 1Как сделать так, чтобы весь список GeoPoint отображался на картах Google?
  • 1Двигатели, доступные для функции to_excel в пандах
  • 0jQuery — находит CSS в нижней части div при запуске, а не во время анимации при наведении
  • 1загрузка ResourceDictionary из XAML также загружает файлы в память
  • 0Удаление лишних изображений не работает
  • 1Как проверить нулевые значения в SqlDataReader, не используя более одного читателя
  • 1Как вернуть объект из службы отдыха в Java?
  • 1У меня странная проблема с питоном, когда я пытаюсь использовать pycharm

Понравилась статья? Поделить с друзьями:
  • Код ошибки 1143
  • Код ошибки 1142 zoom
  • Код ошибки 1141 приора
  • Код ошибки 1141 калина
  • Код ошибки 1141 ваз