Код ошибки 1054 mysql

При использовании ряда CMS (например, DLE, vBulletin и др.) временами возникает ошибка mysql с номером 1054.

При использовании ряда CMS (например, DLE, vBulletin и др.) временами возникает ошибка mysql с номером 1054.

Текст ошибки Unknown column ‘ИМЯ_СТОЛБЦА’ in ‘field list’ в переводе означает «Неизвестный столбец ‘ИМЯ_СТОЛБЦА’ в списке полей.«. Такая ошибка возникает в том случае, если попытаться выбрать (запрос вида select) или изменить (запрос вида update) данные из столбца, которого не существует. Ошибка чаще всего возникает из-за стoронних модулей. Перечислим несколько возможных причин:

  • установлен модуль, расчитанный на более новую версию CMS, чем используемая;
  • при установке модуля не выполнились операции изменения структуры таблиц;
  • после установки сторонних модулей выполнено обновление системы, которое привело к изменению структуры таблиц; при этом модуль не был обновлен на совместимый;
  • Из резервной копии восстановлена более старая база данных, а файлы сайта остались в новой версии.

Пример №1:
Имеется таблица сотрудников подразделения.
Поля: id, фамилия, имя, отчество, год рождения, наличие высшего образования.

create table if not exists employee
(
`id` int(11) NOT NULL auto_increment primary key,
`surname` varchar(255) not null,
`name` varchar(255) not null,
`patronymic` varchar(255) not null,
`year_of_birth` int unsigned default 0,
`higher_education` tinyint unsigned default 0
) ENGINE=MyISAM;

Если обратиться к этой таблице с запросом на выборку несуществующего поля, например пола сотрудника по фамилии Власенко, то результатом будет вышеуказанная ошибка:

mysql> select sex from employee where surname=’Власенко’;

ERROR 1054 (42S22): Unknown column ‘sex’ in ‘field list’

Пример №2:
Воспользуемся той же таблицей из примера 1. Если попытаться указать мужской пол у сотрудника по имени Власенко (выяснилось его имя и стало ясно, что это мужчина), то результатом будет та же ошибка:

mysql> update employee set sex=1 where surname=’Власенко’;

ERROR 1054 (42S22): Unknown column ‘sex’ in ‘field list’

Способы борьбы

Самый корректный способ борьбы в устранении причины ошибки. Например, все обновления сайта рекомендуем выполнять сначала на копии сайта и если ошибок нет, то повторять на рабочем сайте. Если при обновлении возникла ошибка, следует найти способ сделать обновление корректно с учетом версий сторонних модулей.

Если по каким-то причинам корректно избежать ошибки не получилось, можно прибегнуть к симптоматическому лечению, которое состоит в простом добавлении недостающих полей в таблицу.

Запрос на добавление:

ALTER TABLE employee ADD COLUMN sex ENUM(‘male’, ‘female’) DEFAULT ‘female’

Что в переводе означает «Изменить таблицу employee, добавив столбец `пол`, назначив ему тип перечисление(мужской/женский) по умолчанию мужской».

При таком добавлении столбца необходимо учитывать, что у всех записей в таблице в столбце sex появится значение по умолчанию. Если добавлять такой столбец как пол (который не может быть равен null и обязательно присутствует у каждого человека), то просто необходимо сразу же
после этого прописать нужное значение во все записи в таблице. В данном случае с добавлением столбца «пол» нужно будет поменять значение на male у всех сотрудников мужского пола.

Трудности могут возникнуть из-за того, что часто нужно самостоятельно определять тип добавляемого столбца.

Примеры:

a) Запрос:

SELECT faqname, faqparent, displayorder, volatile FROM faq where product
IN (», ‘vbulletin’, ‘watermark’, ‘cyb_sfa’, ‘access_post_and_days’);

Ответ сервера:

Invalid SQL: SELECT faqname, faqparent, displayorder, volatile FROM faq where
product IN (», ‘vbulletin’, ‘watermark’, ‘cyb_sfa’, ‘access_post_and_days’);


MySQL Error: Unknown column ‘faqname’ in ‘field list’

Error Number: 1054

Отсутствует столбец faqname, добавим его. Логика подсказывает, что если имя — то это скорее всего символы, а не целое число или тип datetime. Количество символов заранее, конечно, неизвестно, но редко имя бывает больше чем 255 символов. Поэтому добавим столбец faqname с указанием типа varchar(255):

ALTER TABLE faq ADD faqname varchar(255)

б) Запроc:

UPDATE dle_usergroups set group_name=‘Журналисты’, allow_html=‘0’ WHERE id=‘3’;

Ответ сервера:

Invalid SQL: UPDATE dle_usergroups set group_name=’Журналисты’, allow_html=’0′ WHERE id=’3′;

MySQL Error: Unknown column ‘allow_html’ in ‘field list’

Error Number: 1054

Отсутствует столбец allow_html, добавим его. Смотрим на то значение, которое туда пытается вставить запрос, видим 0. Скорее всего этот столбец может принимать два значения — разрешить/не разрешить (1 или 0), то есть однобайтное целое число вполне подойдёт. Поэтому добавим столбец allow_html с указанием типа tinyint:

ALTER TABLE faq ADD allow_html tinyint

Таким образом можно составить шаблон для «лечения» таких проблем: ALTER TABLE [a] ADD [b] [c];, где

a — имя таблицы, откуда выбираются (или где обновляются) данные;

b — имя столбца, который нужно добавить;

c — тип данных.

Примеры (во всех примерах идёт работа с таблицей dle_usergroups):

1) Запрос:

UPDATE dle_usergroups set group_name=‘Журналисты’, allow_html=‘0’ WHERE id=‘3’;

Ответ сервера:

Invalid SQL: UPDATE dle_usergroups set group_name=’Журналисты’, allow_html=’0′ WHERE id=’3′;

MySQL Error: Unknown column ‘allow_html’ in ‘field list’

Error Number: 1054

Решение:

a=dle_usergroups, b=allow_html, c=tinyint, то есть

ALTER TABLE dle_usergroups ADD allow_html tinyint

Для того, чтобы выполнить исправляющий ошибку запрос, необходимо воспользоваться каким-либо mysql-клиентом. В стандартной поставке mysql всегда идёт консольный клиент с названием mysql (в windows mysql.exe). Для того, чтобы подключиться к mysql выполните команду

mysql -hНАЗВАНИЕ_ХОСТА -uИМЯ_ПОЛЬЗОВАТЕЛЯ -pПАРОЛЬ ИМЯ_БАЗЫ_ДАННЫХ,

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

В том случае, если работа происходит на чужом сервере (например, арендуется хостинг) и нет возможности воспользоваться mysql-клиентом из командной строки (не всегда хостеры представляют такую возможность), можно воспользоваться тем инструментом, который предоставляет хостер — например, phpMyAdmin, и в нём ввести нужный sql-запрос.

В то же время наиболее подходящий инструмент для работы с mysql — это MySQL Workbench — разработка создателей mysql с достаточно удобным пользовательским интерфейсом.

Если же нет возможности подключиться к mysql напрямую (например из-за ограничений файрвола), то в ряде случаев возможно удалённо подключиться к MySQL-серверу через SSH-туннель.

2) Запрос:

UPDATE dle_usergroups set group_name=‘Журналисты’, allow_subscribe=‘0’ WHERE id=‘3’;

Ответ сервера:

Invalid SQL: UPDATE dle_usergroups set group_name=’Журналисты’, allow_subscribe=’0′ WHERE id=’3′;

MySQL Error: Unknown column ‘allow_subscribe’ in ‘field list’

Error Number: 1054

Решение:
a=dle_usergroups, b=allow_subscribe, c=tinyint, то есть

ALTER TABLE dle_usergroups ADD allow_subscribe tinyint

3) Запрос:

SELECT faqname, faqparent, displayorder, volatile FROM faq where product IN (», ‘vbulletin’, ‘watermark’, ‘cyb_sfa’, ‘access_post_and_days’);

Oтвет сервера:

InvalidSQL: SELECT faqname, faqparent, displayorder, volatile FROM faq where product IN (», ‘vbulletin’, ‘watermark’, ‘cyb_sfa’, ‘access_post_and_days’);

MySQL Error: Unknown column ‘faqname’ in ‘field list’

Error Number: 1054

Решение:
a= faq, b=faqname, c=varchar(255), то есть

ALTER TABLE faq ADD faqname varchar(255)

Результат

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

© Все права на данную статью принадлежат порталу webew.ru.
Перепечатка в интернет-изданиях разрешается только с указанием автора
и прямой ссылки на оригинальную статью. Перепечатка в печатных
изданиях допускается только с разрешения редакции.

When you execute a MySQL statement, you may sometimes encounter ERROR 1054 as shown below:

mysql> SELECT user_name FROM users;
ERROR 1054 (42S22): Unknown column 'user_name' in 'field list'

The ERROR 1054 in MySQL occurs because MySQL can’t find the column or field you specified in your statement.

This error can happen when you execute any valid MySQL statements like a SELECT, INSERT, UPDATE, or ALTER TABLE statement.

This tutorial will help you fix the error by adjusting your SQL statements.

Let’s start with the SELECT statement.

Fix ERROR 1054 on a SELECT statement

To fix the error in your SELECT statement, you need to make sure that the column(s) you specified in your SQL statement actually exists in your database table.

Because the error above says that user_name column is unknown, let’s check the users table and see if the column exists or not.

To help you check the table in question, you can use the DESCRIBE or EXPLAIN statement to show your table information.

The example below shows the output of EXPLAIN statement for the users table:

mysql> EXPLAIN users;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| username     | varchar(25) | NO   |     |         |       |
| display_name | varchar(50) | NO   |     |         |       |
| age          | int         | YES  |     | NULL    |       |
| comments     | text        | YES  |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+

From the result above, you can see that the users table has no user_name field (column)

Instead, it has the username column without the underscore.

Knowing this, I can adjust my previous SQL query to fix the error:

SELECT username FROM users;

That should fix the error and your SQL query should show the result set.

Fix ERROR 1054 on an INSERT statement

When you specify column names in an INSERT statement, then the error can be triggered on an INSERT statement because of a wrong column name, just like in the SELECT statement.

First, you need to check that you have the right column names in your statement.

Once you are sure, the next step is to look at the VALUES() you specified in the statement.

For example, when I ran the following statement, I triggered the 1054 error:

mysql> INSERT INTO users(username, display_name) 
    ->   VALUES ("jackolantern", Jack);
ERROR 1054 (42S22): Unknown column 'Jack' in 'field list'

The column names above are correct, and the error itself comes from the last entry in the VALUES() function.

The display_name column is of VARCHAR type, so MySQL expects you to insert a VARCHAR value into the column.

But Jack is not a VARCHAR value because it’s not enclosed in a quotation mark. MySQL considers the value to be a column name.

To fix the error above, simply add a quotation mark around the value. You can use both single quotes or double quotes as shown below:

INSERT INTO users(username, display_name) 
  VALUES ("jackolantern", 'Jack');

Now the INSERT statement should run without any error.

Fix ERROR 1054 on an UPDATE statement

To fix the 1054 error caused by an UPDATE statement, you need to look into the SET and WHERE clauses of your statement and make sure that the column names are all correct.

You can look at the error message that MySQL gave you to identify where the error is happening.

For example, the following SQL statement:

UPDATE users
SET username = "jackfrost", display_name = "Jack Frost"
WHERE user_name = "jackolantern";

Produces the following error:

ERROR 1054 (42S22): Unknown column 'user_name' in 'where clause'

The error clearly points toward the user_name column in the WHERE clause, so you only need to change that.

If the error points toward the field_list as shown below:

ERROR 1054 (42S22): Unknown column 'displayname' in 'field list'

Then you need to check on the SET statement and make sure that:

  • You have the right column names
  • Any string type values are enclosed in a quotation mark

You can also check on the table name that you specified in the UPDATE statement and make sure that you’re operating on the right table.

Next, let’s look at how to fix the error on an ALTER TABLE statement

Fix ERROR 1054 on an ALTER TABLE statement

The error 1054 can also happen on an ALTER TABLE statement.

For example, the following statement tries to rename the displayname column to realname:

ALTER TABLE users 
  RENAME COLUMN displayname TO realname;

Because there’s no displayname column name in the table, MySQL will respond with the ERROR 1054 message.

Conclusion

In short, ERROR 1054 means that MySQL can’t find the column name that you specified in your SQL statements.

It doesn’t matter if you’re writing an INSERT, SELECT, or UPDATE statement.

There are only two things you need to check to fix the error:

  • Make sure you’ve specified the right column name in your statement
  • Make sure that any value of string type in your statement is surrounded by a quotation mark

You can check on your table structure using the DESCRIBE or EXPLAIN statement to help you match the column name and type with your statement.

And that’s how you fix the MySQL ERROR 1054 caused by your SQL statements.

I hope this tutorial has been useful for you 🙏

DigitalOcean Referral Badge
Start your VPS now with FREE $100 credit.

As a free, open-source relational database that can cover a lot of use cases, from dynamic web-based discussion boards and blogs to enterprise resource planning software, MySQL has attracted a lot of users and developers over the years.

As its name implies, MySQL uses SQL (Structured Query Language) as its language, with its extensions to the SQL standard to accommodate its unique features.

For users who are not technically inclined, there are also various graphical tools to manage MySQL databases, ranging from enterprise-grade MySQL Workbench to the popular phpMyAdmin.

However, from time to time you still need to use SQL directly to manipulate your MySQL database. The SQL language is versatile and also used in other database management systems, so users familiar with other systems such as Microsoft SQL Server or Oracle PL/SQL will not have any issue operating MySQL.

That said, the error messages are different as MySQL has its own dialect of SQL. In this article, we will talk about Error Code 1054 on MySQL and how to fix it.

When you create a query, be it manipulation (INSERT INTO or UPDATE) or definition (CREATE TABLE), you might encounter Error Code 1054.

This error code will be shown if the column you mentioned in the query does not exist in the database, or if you try to insert the wrong type of data in your SQL statement.

Fixing Error Code 1054 Issue in MySQL

Error Code 1054 in MySQL database when a column was not found.

Error Code 1054 in MySQL database when a column was not found.

To fix the query, the first thing to do is to check whether the column you specified in the query exists in the table. This can be done by using the query EXPLAIN table_name;

After issuing the query, the MySQL console will display the table structure, and from there you can fix your query so that your query only contains the right columns.

Using EXPLAIN, you will also see the data types of the columns in a certain table. If, for example, you inserted alphanumeric characters to a column with VARCHAR data type, your query will return the 1054 error.

Therefore, it is a good practice to use EXPLAIN before writing any INSERT or UPDATE queries to avoid Error Code 1054.

For example you a table named “wp_users” and you want to get the information about the table. You can simply type:

EXPLAIN wp_users;

It will then output something like this:

+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| user_id      | int         | NO   |     |         |       |
| display_name | varchar(50) | NO   |     |         |       |
| user_age     | int         | YES  |     | NULL    |       |
| user_desc    | text        | YES  |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+

And if you issue this query:

SELECT username FROM wp_users;

You will see the following error:

ERROR 1054 (42S22): Unknown column 'username' in 'field list'

The solution is to change the column name to the right one by referring to the EXPLAIN output:

SELECT user_id FROM wp_users;

Then, the query will return the data inside the user_name column properly.

Since you’re here, you want also want to read our guide on how to reset MySQL root password on Debian/Ubuntu & CentOS.

Solving Error Code 1054 When Using INSERT Statement

Similarly, when you issue this command to insert a new record in the table:

mysql> INSERT INTO wp_users(user_id, display_name)
-> VALUES ("whoami”, “Who Am I”);
ERROR 1054 (42S22): Unknown column 'user_id' in 'field list'

It will fail because user_id is set to accept integers only, not characters. Refer to the EXPLAIN output and correct the query to reflect the right column and data type.

mysql> INSERT INTO wp_users(user_id, display_name)
-> VALUES ("69”, “Who Am I”);

The corrected query will then change the display name of users with the ID “69” to “Who Am I”. The query will no longer return Error 1054 because the column name and data type have been aligned according to the table.

Conclusion

The main thing to prevent this issue in MySQL is always to make sure you know your table well. You can get to know your column well by using the EXPLAIN statement or simply view your table using phpMyAdmin or other similar tools.

We are a bunch of people who are still continue to learn Linux servers. Only high passion keeps pushing us to learn everything.

MySQL error code 1054 occurs if we forget to add single quotes while inserting a varchar value or due to any missing column.

Here at Bobcares, we have seen several causes for this error while troubleshooting MySQL issues as part of our Server Management Services for web hosts and online service providers.

Today we’ll take a look at the cause for this error and how to fix it.

Why does MySQL error code 1054 occur

Now let’s take a look at what causes this error message to occur. There are different reasons for this error to occur and they are:

1. A table having any missing column

2. Forgetting to add single quotes while inserting a varchar value

3. If there is any mismatch between the CREATE_TABLE statements and UPDATE

4. If the column name in the CREATE TABLE and the UPDATE are not the same. In cases, they might look the same but there may be unprintable characters or they may have Unicode characters that look the same but actually are different code points.

How we fix MySQL error code 1054

This error can occur due to many reasons and also the solution will differ according to them. Here are some of the solutions that our Engineers provide to our customers.

1. The table structure is very crucial for understanding and fixing the error. To do that, we check the database of the working site on the localhost. Then with phpMyAdmin, we will export the only table that has a problem on the live site.

For that, we navigate to the database of localhost site >> click on Export tab >> select the table to export and click Go.

We then save the file and open it using the code editor. At the very beginning, the table structure will be described as shown below in the image.

MySQL error code 1054

Then we Construct the ALTER SQL query which will add the missing column in the database table on our live site.

For that, we use the below query.

ALTER TABLE <table_name> ADD <column_name> <datatype> AFTER <after_column>

You can also see the structure of the table by clicking on the structure tab in phpMyAdmin.

2. We update the single quotes around the string value to fix this error if it is missing.

3. We also make sure that there are no unnecessary spaces or characters in the table name mentioned

4. If necessary we also alter the column name so as to contain only printable ASCII characters

[Need any further assistance in fixing MySQL errors? – We’re available 24*7]

Conclusion

In short, This error can arise due to many reasons that include any missing column, missing single quotes while inserting a varchar value, CREATE_TABLE, and UPDATE statements not being identical and so on. Today, we saw the resolution to this MySQL error.

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»;

MySQL error code 1054 happens if we forget to add single quotes while inserting a varchar value or due to any missing column.

Here at Ibmi Media, We have seen several request from our customers regarding MySQL issues and in particular the «MySQL error code 1054«.

In this context, we will discuss the causes of common MySQL errors like this and how to fix them.

What causes MySQL error code 1054?

From our experience in handling and finding solutions to MySQL problems, below are the common reasons why this error happens;
1. When there is an error in the CREATE_TABLE and UPDATE statements.
2. When there is a missing column in a Database table.
3.
When you do not use the correct quote when dealing with a Varchar
value. It is recommend to use single quotes when inserting a varchar
character.
4. When the name of a column does not align with what is being implemented in an UPDATE statement.

Ways to fix MySQL error code 1054

Our
Support Team found some ways to go about fixing this error and we will
share them below. You can follow the following steps to solve MySQL
issues;

1. It is important that when creating a table, ensure that you remove any inappropriate spacing or incorrect characters.
2. We ensure that the naming of the column follows the ASCII characters standard.
3. Always use single quotes when dealing with a string  and varchar characters.
4.
To do a proper fix, you should troubleshoot the database in a local
environment by exporting from the phpmyadmin it to your local machine
Localhost. Then edit the SQL file and look into the affected table to
see if single quotes was not used properly.

Afterwards, you can make an ALTER SQL query to add any missing column in the Table. To do this, use the query below;
ALTER TABLE <table_name> ADD <column_name> <datatype> AFTER <after_column>

[Do you need support in fixing MySQL errors? We can help you Today.]

Conclusion

In
summary, MySQL error code 1054 is as a result of a missing column, or when a
single quote is not used in the Create or Update statements. To fix
other Database errors, Consult our MySQL Experts Today.

Доброго времени суток. При выполнении запроса выдает ошибку [Err] 1054 — Unknown column ‘stitle.subcat’ in ‘where clause’

UPDATE ad_copy, (SELECT CONCAT_WS(" - ", ad_copy.title, stitle.ttitle) AS `p` from ad_copy, stitle 
where ad_copy.category = stitle.subcat ORDER BY RAND()) `p` set `title` = `p` where ad_copy.category = stitle.subcat

Суть — запрос должен брать данные из одной таблицы и дополнять уже имеющиеся данные ими. Заранее спасибо за помощь!


  • Вопрос задан

    более трёх лет назад

  • 5350 просмотров

Ошибка вполне понятна, во внешнем WHERE таблица stitle не определена, соответственно колонка stitle.subcat тоже.
Запрос несколько бредовый, ORDER BY RAND() — наихудший по скорости вариант, как правило можно обойтись без него. Лучше скажите, какой результат хотите получить.

UPDATE `ad_copy` AS `a` 
    LEFT JOIN (
        SELECT `a`.`title`, (
            SELECT `s`.`ttitle`
                FROM `stitle` AS `s` 
                WHERE `a`.`category` = `s`.`subcat` 
                ORDER BY RAND() 
                LIMIT 1
            ) AS `ttitle`
        FROM `ad_copy` AS `a`
    ) AS `s` USING(`title`) 
    SET `a`.`title` = CONCAT_WS(" - ", `a`.`title`, `s`.`ttitle`)

1. При каждом следующем запросе к ad_copy.title будет дописываться новое значение?
2. Если количество записей в каждой подкатегории небольшое, то ORDER BY RAND() не сильно скажется на производительности. Если большое — может оказаться, что лучше делать внешними средствами.

Пригласить эксперта

UPDATE 
ad_copy a
JOIN stitle  s ON (a.category = s.subcat)
SET a.`title` = CONCAT_WS( " - ",a.title,s.ttitle)

Сделал так. Мне надо чтобы в колонку ttitle добавлялось случайное значение из stitle…


  • Показать ещё
    Загружается…

13 февр. 2023, в 00:07

500 руб./за проект

13 февр. 2023, в 00:01

25000 руб./за проект

12 февр. 2023, в 23:40

100000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:
  • Код ошибки 1049 синий экран виндовс 7
  • Код ошибки 103 1с эдо
  • Код ошибки 10200 домофон hikvision
  • Код ошибки 1002 рокстар
  • Код ошибки 1 bf4