Ошибка 1146 что это

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,54812 gold badges57 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.5k22 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,77311 gold badges42 silver badges72 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,70521 silver badges35 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,3925 gold badges19 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,9201 gold badge17 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.3k3 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,2819 gold badges46 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…

vvns's user avatar

vvns

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

4867 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,34311 gold badges55 silver badges98 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,6752 gold badges19 silver badges42 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

3952 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,3661 gold badge39 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

18 ответов

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

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

sempasha

Поделиться

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

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

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

Мое решение:

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

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

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

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

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

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

carlos

Поделиться

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

DROP TABLE mytable

затем

CREATE TABLE....

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

Jim 007

Поделиться

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

Muhammad Usman

Поделиться

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

thekosmix

Поделиться

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

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

blarg

Поделиться

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

Короче:

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

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

SteveCinq

Поделиться

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

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

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

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

Xin

Поделиться

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

Vipin Gurjar

Поделиться

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

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

Kahitarich

Поделиться

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

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

hiropon

Поделиться

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

DauleDK

Поделиться

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

Ayman Al-Absi

Поделиться

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

ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;

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

ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;

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

l0pan

Поделиться

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

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

Amey

Поделиться

Недавно у меня была такая же проблема, но на 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

Поделиться

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

mysql_upgrade -u user -ppassword

Ravi Parekh

Поделиться

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

Oswald

Поделиться

Ещё вопросы

  • 0Толкая значения в моделировании внутри повтора
  • 0Отображение сообщения вне цикла while
  • 0Ширина сетки не фиксируется
  • 0При первом нажатии CSS3 работает, но при втором не работает, почему?
  • 0R или Mysql: изменить значения столбца на ноль, если они отсутствуют в другой строке того же кадра данных
  • 1Общие методы приводят это к T
  • 1курсор падает с CursorIndexOutOfBoundsException
  • 0выбрать все товары из дочерних категорий в родительской категории
  • 0Используя библиотеку PHP Podio, не могу получить данные рейтинга через PodioItem :: get ($ id)
  • 1Java HttpGet, слишком много открытых файлов в сервисной ошибке
  • 1Как читать XML-документ с URL
  • 0AngularJs — нужна помощь, чтобы подключить контроллер к представлению
  • 1Android 8: невозможно изменить режим звонка на бесшумный, когда режим звонка беззвучный
  • 0Чтение текстового файла в структуру и отображение массива
  • 0Получить идентификатор отмеченных флажков в списке одним нажатием кнопки
  • 1Нужно конвертировать действительные значения даты и вывести ошибочные значения в Python
  • 1Как создать объект JSON с ключом и значением, где значение является массивом
  • 0Ошибка jQuery только в IE8 «Объект не поддерживает это свойство или метод»
  • 1Адаптирование spymemcached Java-клиента GetFuture к Guava ListenableFuture
  • 1Не определено ни одного уникального компонента типа [бла]: ожидаемый единственный соответствующий компонент, но найден 2 [moreBlah]
  • 0угловой карма-жасмин юнит тест для контроллера
  • 0Почему я создал потенциальный блуждающий указатель при удалении здесь в деструкторе?
  • 0Почему эта операция не дает мне большей точности?
  • 0ionicSideMenu: отключить перетаскивание для одной стороны, но разрешить для другой?
  • 1Проверка переменных Javascript: (null или undefined) против логического
  • 0неразрешенный внешний символ public __thiscall только в режиме отладки
  • 0Что означает typedef cell (* proc_type) (const std :: vector <cell> &); делать?
  • 0Реализация прокрутки в 2 пальца в приложении Silverlight на Safari на Mac
  • 1После перевода реселлервью перестает слушать сенсорные события
  • 0Проверка имени пользователя удаленной проверки JQuery
  • 0Как увеличить центр экрана?
  • 0OS X 10.10 (yosemite) PHP 5.5.14 — есть ли способ установить поддержку png без HomeBrew
  • 1Компонент сценария служб SSIS — процесс 1 строки из Json в таблицу
  • 0Apache conf для nginx conf, чтобы избежать CORS
  • 0Использование php для обработки нескольких форм на одной странице
  • 1Первая буква не меняется на заглавную при использовании большого количества пробелов между словами
  • 1Struts2 — пересылка по аннотации с динамическим параметром
  • 1скомпилировать файл Java в Eclipse
  • 0Каковы отношения веб-фреймворков и других
  • 1Express.js — обернуть каждое промежуточное ПО / маршрут в «декоратор»
  • 0Чтение всех байтов файла BMP в c ++ и поворот изображения
  • 1Получить индекс значения
  • 0Бинарный столбец SQL, если пользователь играл
  • 0Группа флажков
  • 0Вставка выбранного значения из заполненного MySQL выпадающего
  • 1Python Plotly Sankey Graph не отображается
  • 1Canvas неправильно рисует край при извлечении изображения из спрайта
  • 0Вместо электронной почты идентификатор пользователя идет в базу данных
  • 1Параметры для входа в систему без публикации через REST с использованием Volley
  • 0Как мне сопоставить динамический маршрут в базе данных?

Are you trying to figure out MYSQL replication error 1146?

This is a generic error when we set up the MYSQL replication.

Also, the main reasons for the MYSQL replication error 1146 due to invalid MySQL queries or non-existing SQL queries.

At Bobcares, we often get requests to solve such MYSQL replication errors as part of our Server Management Services.

Today, let’s analyze the cause and see how our Support Team fix it for our customers.

What is MYSQL replication?

Normally, it is a process that enables data from one MySQL database server (the master) to copied automatically to one or more MySQL database servers (the slaves). However, general principles of setting up the MySQL master-slave replication on the same machine are the same for all operating systems.

It is simply copying data from one server to another server. So all the users can share the same data without any inconsistency.

The main Advantages of MySQL Replication includes,

  1. High Performance
  2. Backup and Security
  3. Remote Access

Reasons for MYSQL replication error 1146.

This is a generic error when we discover the slave MySQL server is having a problem replicating data from the master. The main reason for this error is due to invalid MySQL queries or non-existing mysql queries.

Recently one of our customers contacted us with this MYSQL error when he tried to set-up the MYSQL replication. Then he checked the slave status and returned the error code like this.

MYSQL replication error 1146

The above error message shows that the table “db3.table3” does not exist in the slave database. To fix this error, we just simply ignore this error and resume the replication.

How we fix the MYSQL replication error 1146.

So far, we discuss the MYSQL replication and reasons for the replication error 1146. Now let’s see how our Support Engineers fix this error for our customers.

Solution 1

To fix the replication error we follow the below steps.

1. First, we log into the MYSQL.

mysql -u root -p

2. On the MySQL shell, we check the slave status.

mysql> SHOW SLAVE STATUS

The sample result as follows.

mysql> SHOW SLAVE STATUS
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 1.2.3.4
Master_User: slave_user
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.001089
Read_Master_Log_Pos: 269214467
Relay_Log_File: slave-relay.000234
Relay_Log_Pos: 100125935
Relay_Master_Log_File: mysql-bin.001079
Slave_IO_Running: Yes
Slave_SQL_Running: No
Replicate_Do_DB: mydb
Last_Errno: 1146

If anyone of the Slave_IO_Running or Slave_SQL_Running is set as NO, it means the replication is broken.

So, we start to repair the MYSQL replication.

3. For that, we stop the slave from replication, using the below command.

mysql> STOP SLAVE;

4. Next, we tell the slave to simply skip the invalid SQL query. So we use the below command.

mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1;

This query tells the slave to skip one query (which is the invalid one that caused the replication to stop).  If we like to skip two queries, we use the following code instead.

SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 2;

That’s it.

5. Again, we start the slave.

mysql> START SLAVE;

6. After that, we check if replication is working again.

mysql> SHOW SLAVE STATUS

mysql> SHOW SLAVE STATUS
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 1.2.3.4
Master_User: slave_user
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.001089
Read_Master_Log_Pos: 269214467
Relay_Log_File: slave-relay.000234
Relay_Log_Pos: 100125935
Relay_Master_Log_File: mysql-bin.001079
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB: mydb
Last_Errno: 1146 

Both Slave_IO_Running and Slave_SQL_Running are set to Yes now. And the replication is running without any error.

Then we leave the MySQL shell.

mysql> quit;
Solution 2

Recently another customer contacted us with the MYSQL replication error. He also tried to set up the MYSQL replication and returns the error as follows.

[ERROR] Slave I/O: Unable to load replication GTID slave state from mysql.gtid_slave_pos: Table 'mysql.gtid_slave_pos' doesn't exist, Internal MariaDB error code: 1146

Next, he tried mysql_upgrade` and it looked already up to date, so he tried –force, which gave:

mysql.gtid_slave_pos
Error : Table 'mysql.gtid_slave_pos' doesn't exist in engine
status: Operation failed

Then he checked the dB/mysql folder and found that the .frm and .ibd is already existing.

gtid_slave_pos.frm
gtid_slave_pos.ibd

Then we just removed the files and recreated the table, which solved the error.

1. So we go to the mysql folder and drop the following files using the command.

rm gtid_slave_pos.frm
rm gtid_slave_pos.ibd

Also, to create the table we use the command:

CREATE TABLE table_name (column_name column_type);

2. Then, we stop and start the slave

mysql]> stop slave;
mysql]> start slave;

This fixes the error.

[Need more assistance for MYSQL replication error 1146? We’ll help you]

Conclusion

In short, the main reasons for the MYSQL replication error 1146 is invalid MySQL queries or non-existing SQL queries. Today, we saw how our Support Engineers fix this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

1

Собственно код ошибки:

Не поймем что за таблицу требует?

Возникает ошибка при попытке переключится на «новый раздел товаров»

При этом в карточке редактирования самого товара переключится на «новый раздел» можно, но тогда уже не дает зайти в саму вкладку товары. Пока опять не зайду в редактор товара и не переключу на старый режим.

Ошибка стала возникать после обновления до версии 2.7.1.727

12 комментариев

  • популярные
  • новые
  • старые


  • +2

    Выполните SQL-запросы в phpMyAdmin на хостинге для вашей базы данных:

    CREATE TABLE `shop_presentation` (
      `id` int(10) UNSIGNED NOT NULL,
      `parent_id` int(10) UNSIGNED DEFAULT NULL,
      `name` varchar(255) DEFAULT NULL,
      `creator_contact_id` int(11) NOT NULL,
      `use_datetime` datetime DEFAULT NULL,
      `sort_column_id` int(10) UNSIGNED DEFAULT NULL,
      `sort` int(11) NOT NULL DEFAULT '0',
      `sort_order` enum('asc','desc') NOT NULL DEFAULT 'asc',
      `view` enum('table','table_extended','thumbs') NOT NULL DEFAULT 'table',
      `rows_on_page` int(11) NOT NULL DEFAULT '30',
      `browser` varchar(64) DEFAULT NULL,
      `filter_id` int(11) DEFAULT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
    
    ALTER TABLE `shop_presentation`
      ADD PRIMARY KEY (`id`),
      ADD KEY `creator_contact_id` (`creator_contact_id`);



    • +1

      Пустой результат



      • -1

        Вы же просто создали таблицу, которой не было, а затем сделали в ней индексы. Какие результаты ещё вы ожидали увидеть в phpmyadmin, выполняя такой запрос к базе данных? Если получилась новая пустая таблица, то это всё. Больше ничего этот запрос и не должен был делать.

        Вы лучше повторите все старые действия, которые ранее приводили к ошибке, и расскажите изменилось ли что-то или всё осталось как было.



        • +1

          Вроде ничего не изменилось



          • -1

            1364 — это не 1146. Уже определенно что-то изменилось. Может быть не установлен на вновь созданной таблице на колонке ID флаг AUTOINCREMENT. Надо поставить его через phpmyadmin. Полная картина запросов такая. У вас нет одного последнего запроса.

            CREATE TABLE `shop_presentation` (
              `id` int(10) UNSIGNED NOT NULL,
              `parent_id` int(10) UNSIGNED DEFAULT NULL,
              `name` varchar(255) DEFAULT NULL,
              `creator_contact_id` int(11) NOT NULL,
              `use_datetime` datetime DEFAULT NULL,
              `sort_column_id` int(10) UNSIGNED DEFAULT NULL,
              `sort` int(11) NOT NULL DEFAULT 0,
              `sort_order` enum('asc','desc') NOT NULL DEFAULT 'asc',
              `view` enum('table','table_extended','thumbs') NOT NULL DEFAULT 'table',
              `rows_on_page` int(11) NOT NULL DEFAULT 30,
              `browser` varchar(64) DEFAULT NULL,
              `filter_id` int(11) DEFAULT NULL
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
            
            ALTER TABLE `shop_presentation`
              ADD PRIMARY KEY (`id`),
              ADD KEY `creator_contact_id` (`creator_contact_id`);
            
            ALTER TABLE `shop_presentation`
              MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;

            В итоге вот такая должна получиться структура у этой таблицы. Флаг на колонку можно поставить через интерфейс управления базой данных (Действие — Изменить) или запросом (см. выше)



            • +1

              таблица как у вас на скрине есть, вроде все на месте

              Теперь как Вы и писали ругается на отсутствие shop_presentation_columns так же 1146 ошибка

              Ее по тому же принципу создавать как и  shop_presentation ? В плане SQL запрос?



              • -1

                Да, создаете эту таблицу вот такими тремя запросами

                CREATE TABLE `shop_presentation_columns` (
                  `id` int(10) UNSIGNED NOT NULL,
                  `presentation_id` int(10) UNSIGNED NOT NULL,
                  `column_type` varchar(64) NOT NULL,
                  `width` int(11) DEFAULT NULL,
                  `data` text DEFAULT NULL,
                  `sort` int(11) NOT NULL DEFAULT 0
                ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
                
                ALTER TABLE `shop_presentation_columns`
                  ADD PRIMARY KEY (`id`),
                  ADD KEY `presentation_id` (`presentation_id`);
                
                ALTER TABLE `shop_presentation_columns`
                  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;



                • +1

                  И вновь ругается уже на

                  Table … shop_filter’ doesn’t exist code 1146

                  (где троеточие там название аккаунта и сайта)



                  • +1

                    Напишите нам в службу поддержки — изучим ситуацию подробнее и попробуем предложить решение.



                    • +1

                      Спасибо, тех поддержка базу поправили.



                    • -1

                      У вас нет целой россыпи таблиц. Надо чинить базу (восполнять потери). Возможно при обновлении не создались нужные таблицы, либо что-то ещё пошло не так.

                      Напишите в службу ТП. Они вам помогут сделать коррекцию базы и проверят правильность обновления.

                      Конечно можно тут на форуме и дальше продолжать до тех пор, пока всё не пройдет (сравнить структуры БД, найти недостающие таблицы, сравнить версии ПО и т.д., потому что сама по себе эта процедура не сложная), но обращение в ТП однозначно поможет вам сэкономить время.

                      В вашей ситуации специалист, имеющий доступ и должные навыки, быстрее всё починит без лишних слов.



                    • 0

                      И ещё, раз пошла такая пляска, то проверьте наличие таблицы shop_presentation_columns. Вдруг потом ещё и на неё ругаться будет, если её нет. По логике она должна быть тоже и, если что-то пошло не так у вас при обновлении, то её может не оказаться на месте.

                      Добавить комментарий

                      We may encounter mysqldump error 1146 table doesn’t exist while we perform the database dump.

                      Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related MySQL queries.

                      In this context, we shall look into how to fix this error in Plesk and Directadmin.

                      Nature of mysqldump: Got error: 1146: Table doesn’t exist

                      Recently, while performing the database dump, some of our users notice the error:

                      mysqldump: Got error: Table ‘myDatabase.table’ doesn‘t exist when using LOCK TABLES

                      In order to check, we go to MySQL:

                      mysql -u admin -p

                      Then we query for the tables:

                      show tables;

                      Here, we can find the table. However, when we query for that particular table:

                      select * from table

                      We get the same error:

                      ERROR 1146 (42S02): Table 'myDatabase.table' doesn't exist

                      We can try to repair it via:

                      mysqlcheck -u admin -p --auto-repair --check --all-databases

                      However, the error may prevail:

                      Error : Table 'myDatase.table' doesn't exist

                      The main causes of error 1146: Table doesn’t exist:

                      • InnoDB tablespace might have been deleted and recreated but corresponding .frm files of InnoDB tables from the database directory were not removed, or .frm files were moved to another database.
                      • Incorrect permissions and ownership on table’s files in MySQL data directory.
                      • A corrupt table data.

                      How to fix mysqldump: Got error: 1146: Table doesn’t exist ?

                      On Plesk

                      1. Initially, we try to connect to the server using SSH

                      2. Then we try to use —skip-lock-tables parameter with mysqldump to skip lock tables.

                      For example,

                      #mysqldump –skip-lock-tables -u<db_user> -p<db_user_password> database_name > /root/database_dump.sql

                      3. If it does not help, we check permissions and ownership on the table’s files in the MySQL data directory for the database that fails to dump. It should be mysql for both owner and group:

                      i. Find data dir location:

                      RHEL/CentOS

                      #grep datadir /etc/my.cnf
                      datadir=/var/lib/mysql

                      Debian/Ubuntu

                      #grep -iR datadir /etc/mysql*
                      /etc/mysql/mysql.conf.d/mysqld.cnf:datadir = /var/lib/mysql

                      ii. Check permissions:

                      # ls -la /var/lib/mysql/example_db/

                      iii. Fix permissions:

                      # chown -R mysql:mysql /var/lib/mysql/example_db/

                      4. If it is still not possible, we try to repair the table in the error using the native MySQL repair tool:

                      # plesk db
                      mysql> use example_db;
                      mysql> REPAIR TABLE <TABLENAME>;

                      Note: We need to replace the <TABLENAME> with table name in the error message.

                      5. If the issue still persists, most probably ibdata* file does not have the info about the table. However, the orphaned .frm files still persist on the file system. We remove it:

                      i. To verify that table is corrupt or not, we run:

                      # plesk db
                      mysql> use database example_db;
                      mysql> desc <TABLENAME>;

                      If this command fails with the error, it means that ibdata* does not have the information about the table and we need to remove the .frm file.

                      ii. To do so, we browse to the database directory /var/lib/mysql/example_db/ and move .frm file:

                      # cd /var/lib/mysql/example_db/
                      # mv <TABLENAME>.frm /root/<TABLENAME>.frm

                      6. If these options fail and we have no valid backups to restore, the only available option to save the database is to dump it with the innodb_force_recovery option.

                      On Directadmin

                      Suppose, we get the error for the User database and Table:

                      mysqldump error output: mysqldump: Got error: 1146: Table ‘user_db.table‘ doesn’t exist when using LOCK TABLES

                      1. In this case, we check to see if there are any other data files, or if it’s just the .frm file:

                      cd /var/lib/mysql/user_db
                      ls -la table.*

                      If it’s just the table.frm file, then the rest of the data is likely lost. However, we may be able to rebuild the table.

                      2. To do so, we need to read the .frm file. We need the mysqlfrm tool for that, eg: yum install mysql-utilities. Once we install it, we check if it can be read:

                      mysqlfrm –diagnostic table.frm

                      This can output the full CREATE TABLE syntax.  We save this somewhere, until the end of the last ; character.

                      Note, we can either delete the “CHARACTER SET “,  or change it to the correct charset.

                      3. Then, we remove the broken table.  To do so, we login to /phpMyAdmin and run the query:

                      DROP TABLE user_db.table

                      4. Finally, we run the CREATE TABLE query from above, to rebuild the table.

                      [Need to fix Mysql errors? We’d be happy to assist you. ]

                      Понравилась статья? Поделить с друзьями:
                    • Ошибка 1146 на сайте
                    • Ошибка 1146 table doesn t exist
                    • Ошибка 1146 joomla 3
                    • Ошибка 1146 iphone
                    • Ошибка 1145 iphone 5s