Field list mysql ошибка

Дата: 25.11.2013

Автор: Даниил Каменский , dkamenskiy (at) yandex (dot) ru

При использовании ряда 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

Дата публикации: 25.11.2013

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

The MySQL unknown column in field list error happens when you put a column name in your SQL script that can’t be found by MySQL.

For example, suppose you have a table named students with the following data:

+----+---------+---------+-------+--------+
| id | name    | subject | score | gender |
+----+---------+---------+-------+--------+
|  1 | Sarah   | Math    |     9 | male   |
|  2 | Natalia | Math    |     8 | female |
|  3 | Christ  | English |     5 | male   |
+----+---------+---------+-------+--------+

When you try to insert into a column that doesn’t exist in the table, MySQL will throw the said error:

INSERT INTO students(student_name) VALUES (Michael);

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

The error above is because there’s no student_name column in the students table.

Next, the error can also be triggered because you didn’t use quotes for the string values as follows:

INSERT INTO students(name) VALUES (Michael);

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

The value Michael must be wrapped in quotations ('' or "") or MySQL will think you are trying to insert values from another column to the target column.

The error can also be triggered by other things that make MySQL think that your column doesn’t exist.

One example is that you may trigger the error when calling a variable without the @ symbol as shown below:

SET @myVar="Hello";
SELECT myVar;

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

Another thing that could trigger the error is that you’re using backticks to wrap literal values, as in the following UPDATE statement:

UPDATE students SET subject = `English` WHERE id = 1;

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

The English value for the subject field above should be wrapped by quotations (single or double) instead of backticks.

The error can also be triggered when you have a SELECT query that has different tables between the SELECT clause and the FROM clause as shown below:

SELECT students.name FROM cities;

-- ERROR 1054 (42S22): Unknown column 'students.name' in 'field list'

This is because you are trying to query a column owned by students table from the cities table, which doesn’t match.

Finally, the error can also be caused by invisible characters lurking in your script that can’t be seen when you copy and paste it from other sources.

The only way to remove invisible characters is by rewriting the statements manually.

Summary

The tutorial above has listed the most common cause for MySQL unknown column in field list error.

There are many variations of SQL statements that can cause this error, so this error doesn’t really help you find the cause without understanding how MySQL syntax works.

I hope this tutorial has given you some guidelines on fixing the error. Good luck! 👍

I keep getting MySQL error #1054, when trying to perform this update query:

UPDATE MASTER_USER_PROFILE, TRAN_USER_BRANCH
SET MASTER_USER_PROFILE.fellow=`y`
WHERE MASTER_USER_PROFILE.USER_ID = TRAN_USER_BRANCH.USER_ID
AND TRAN_USER_BRANCH.BRANCH_ID = 17

It’s probably some syntax error, but I’ve tried using an inner join instead and other alterations, but I keep getting the same message:

Unknown column 'y' in 'field list' 

ROMANIA_engineer's user avatar

asked Aug 28, 2009 at 10:38

me_here's user avatar

0

Try using different quotes for «y» as the identifier quote character is the backtick (`). Otherwise MySQL «thinks» that you point to a column named «y».

See also MySQL 8 Documentation

Please use double-/single quotes for values, strings, etc.
Use backticks for column-names only.

answered Aug 28, 2009 at 10:57

tuergeist's user avatar

tuergeisttuergeist

9,1113 gold badges37 silver badges58 bronze badges

1

Enclose any string to be passed to the MySQL server inside single quotes, e.g.:

$name = "my name"
$query = " INSERT INTO mytable VALUES ( 1 , '$name') "

Note that although the query is enclosed between double quotes, you must enclose any string in single quotes.

informatik01's user avatar

informatik01

16k10 gold badges73 silver badges104 bronze badges

answered Dec 29, 2009 at 11:45

ShoushouLeb's user avatar

ShoushouLebShoushouLeb

6395 silver badges2 bronze badges

5

You might check your choice of quotes (use double-/ single quotes for values, strings, etc and backticks for column-names).

Since you only want to update the table master_user_profile I’d recommend a nested query:

UPDATE
   master_user_profile
SET
   master_user_profile.fellow = 'y'
WHERE
   master_user_profile.user_id IN (
      SELECT tran_user_branch.user_id
      FROM tran_user_branch WHERE tran_user_branch.branch_id = 17);

Tim Cooper's user avatar

Tim Cooper

157k38 gold badges330 silver badges279 bronze badges

answered Aug 28, 2009 at 11:08

0

Just sharing my experience on this. I was having this same issue. The insert or update statement is correct. And I also checked the encoding. The column does exist.
Then! I found out that I was referencing the column in my Trigger.
You should also check your trigger see if any script is referencing the column you are having the problem with.

answered Nov 20, 2019 at 2:11

Dean Chiu's user avatar

Dean ChiuDean Chiu

1,3251 gold badge13 silver badges13 bronze badges

2

In my case, it was caused by an unseen trailing space at the end of the column name. Just check if you really use «y» or «y » instead.

answered Oct 21, 2016 at 10:26

Aminah Nuraini's user avatar

Aminah NurainiAminah Nuraini

17.9k8 gold badges89 silver badges107 bronze badges

While working on a .Net app build with EF code first, I got this error message when trying to apply my migration where I had a Sql("UPDATE tableName SET columnName = value"); statement.

Turns out I misspelled the columnName.

answered Feb 14, 2018 at 9:59

Masterchief's user avatar

MasterchiefMasterchief

1073 silver badges8 bronze badges

1

If it is hibernate and JPA. check your referred table name and columns might be a mismatch

answered Jul 24, 2019 at 6:30

Poorna's user avatar

PoornaPoorna

1911 silver badge5 bronze badges

Just sharing my experience on this. I was having this same issue. My query was like:

select table1.column2 from table1

However, table1 did not have column2 column.

answered Feb 1, 2020 at 4:43

user674669's user avatar

user674669user674669

10.4k15 gold badges72 silver badges103 bronze badges

1

In my case, the Hibernate was looking for columns in a snake case, like create_date, while the columns in the DB were in the camel case, e.g., createDate.
Adding

spring:
  jpa:
    hibernate:
      naming: # must tell spring/jpa/hibernate to use the column names as specified, not snake case
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl

to the application.ymlhelped fix the problem.

answered Dec 23, 2020 at 13:02

Katia Savina's user avatar

In my case, I used a custom table alias for the FROM table, but I used the default table alias (MyTable) in the field list instead of the custom table alias (t1). For example, I needed to change this…

mysql> SELECT MyTable.`id` FROM `MyTable` t1;

…to this…

mysql> SELECT t1.`id` FROM `MyTable` t1;

answered Sep 15, 2021 at 17:11

Arya's user avatar

AryaArya

5662 gold badges9 silver badges22 bronze badges

In my case I had misspelled the column name in the table’s trigger. Took me a while to connect the error message with the cause of it.

answered Mar 13, 2022 at 21:46

constant283's user avatar

I too got the same error, problem in my case is I included the column name in GROUP BY clause and it caused this error. So removed the column from GROUP BY clause and it worked!!!

answered Jun 28, 2018 at 5:55

Suresh's user avatar

SureshSuresh

1,4812 gold badges22 silver badges27 bronze badges

I got this error when using GroupBy via LINQ on a MySQL database. The problem was that the anonymous object property that was being used by GroupBy did not match the database column name. Fixed by renaming anonymous property name to match the column name.

.Select(f => new 
{
   ThisPropertyNameNeedsToMatchYourColumnName = f.SomeName
})
.GroupBy(t => t.ThisPropertyNameNeedsToMatchYourColumnName);

answered Jul 31, 2019 at 19:07

Eternal21's user avatar

Eternal21Eternal21

4,0902 gold badges47 silver badges62 bronze badges

A query like this will also cause the error:

SELECT table1.id FROM table2

Where the table is specified in column select and not included in the from clause.

Aaron Meese's user avatar

Aaron Meese

1,6362 gold badges22 silver badges32 bronze badges

answered May 16, 2017 at 16:58

hogarth45's user avatar

hogarth45hogarth45

3,3571 gold badge22 silver badges27 bronze badges

in this tutorial, we’ll learn how to fix “UNKNOWN COLUMN IN ‘FIELD LIST’”. Sometimes, We’re are getting errors after each insert or update to the MySQL table.

The message is “Unknown column ‘column-name’ in ‘field list’” while this column was existing in this table.

The most common causes of the error “MySQL: Unknown column in field list” are listed in this tutorial.

The MySQL unknown column in field list error happens when you put a column name in your SQL script that can’t be found by MySQL.

I have created an employee table and inserted data as below:

The following error message is thrown by MySQL when you attempt to insert data into a column that doesn’t exist in the table:

Option 1: The column name is not found

Let’s create a SQL to insert data into the non-existence column:

INSERT INTO employees(emp_name) VALUES ('Tim');

The error below is because there’s no emp_name column in the employees table.

Option 2: Column value is not wrapped with Quotes

Sometimes, We didn’t use quotes for the string values and also throw the same errors.

INSERT INTO employees(emp_name) VALUES (Tim);

The error:

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

The value Tim must be wrapped in quotations (” or “”). Your attempt to put values into the target column from a different column will be misinterpreted by MySQL.

Option 3: calling a variable without the @ symbol

The same error will throw if calling a variable without the @ symbol.

SET @name="Tim";
SELECT name;

The Error message:

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

Option 4: MySQL Trigger issue

Sometimes, we have defined triggers into MySQL that have columns that do not exist, t ll trigger when any record insert into MySQL.

create trigger insert_on_emp
after insert
on employee for each row
begin
insert into department (name, dept) values (new.name, 'devops');
end##
delimiter ;

To solve the error I will need either rewrite the trigger and remove dept column from the insert command or alter table ‘department’ and add column ‘dept’.

Tech-Assured a Solution from Enlink


By Tech-Assured     

January 27, 2021  28030 Views


MySQL-Error-1054

If you see this error, it means you have forgotten something while creating table.

Let’s see the causes & fixes to it

Possible causes for Error 1054


  • Missing column in a table.
  • Single quotes missing while inserting varchar value.
  • Mismatch between CREATE_TABLE and UPDATE.

Solution


  • Check the database of the working site on localhost site and export the problematic table on the live site.
  • Save the file and open it using code editor.
  • Construct the ALTER SQL query to add missing column in database table.
  • ALTER TABLE<table_name>ADD<column_name><datatype>AFTER<after_column>

Apart from these causes, there could be many other reasons to this error code, if the issue still persists…

Ask for help –
Our Support Engineers will walk you through the steps…

Tech-Assured can help you deploy best IT practices and mitigate risks with a fully compliant IT framework.

Hewson’s View | This was an election budget on steroids liothyronine online how a little-known agency reveals the web of influence between patient advocates and big pharma

Recommended Posts

Enlink Clients

  • Fiac silver 10 ошибка al6
  • Fhx clash of clans ошибка подключения
  • Fh4gamesave код ошибки e 88 d
  • Fh4 autouwp exe forza horizon 4 ошибка
  • Fg wilson dcp 10 ошибки