Error 1054 unknown column title in field list

Дата: 25.11.2013

Дата: 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. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

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 🙏

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,0013 gold badges35 silver badges57 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

15.8k10 gold badges74 silver badges103 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

156k38 gold badges325 silver badges276 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,2751 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.5k8 gold badges87 silver badges106 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

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

9,96814 gold badges70 silver badges98 bronze badges

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

1611 silver badge5 bronze badges

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

5372 gold badges8 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,3072 gold badges20 silver badges26 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

3,8822 gold badges43 silver badges58 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,3842 gold badges21 silver badges25 bronze badges

answered May 16, 2017 at 16:58

hogarth45's user avatar

hogarth45hogarth45

3,2471 gold badge22 silver badges27 bronze badges

If you’re getting an error that reads something like “ERROR 1054 (42S22): Unknown column ‘tab.ColName’ in ‘on clause”” in MariaDB, here are three likely causes:

  • The column doesn’t exist.
  • You’re trying to reference an aliased column by its column name.
  • Or it could be the other way around. You could be referencing the column with an alias that was never declared.

If a column has an alias, then you must use that alias when referencing it in any ON clause when doing a join against two or more tables. Conversely, if you reference a column by an alias, then you need to ensure that the alias is actually declared in the first place.

Example 1

Here’s an example of code that produces the error:

SELECT 
    c.CatId,
    c.CatName
FROM Cats c
INNER JOIN Dogs d
ON c.DogName = d.DogName;

Result:

ERROR 1054 (42S22): Unknown column 'c.DogName' in 'on clause'

Here I accidentally used c.DogName in the ON clause when I meant to use c.CatName.

In this case, the fix is simple. Use the correct column name:

SELECT 
    c.CatId,
    c.CatName
FROM Cats c
INNER JOIN Dogs d
ON c.CatName = d.DogName;

Example 2

Here’s another example of code that produces the error:

SELECT 
    CatId,
    CatName
FROM Cats
INNER JOIN Dogs d
ON c.CatName = d.DogName;

Result:

ERROR 1054 (42S22): Unknown column 'c.CatName' in 'on clause'

Here I referenced a non-existent alias in the ON clause. I used c.CatName to refer to the CatName column in the Cats table. The only problem is that the Cats table doesn’t have an alias.

To fix this issue, all we have to do is provide an alias for the Cats table:

SELECT 
    CatId,
    CatName
FROM Cats c
INNER JOIN Dogs d
ON c.CatName = d.DogName;

Alternatively, we could remove all references to the alias, and just use the full table name:

SELECT 
    CatId,
    CatName
FROM Cats
INNER JOIN Dogs
ON Cats.CatName = Dogs.DogName;

One thing I should point out is that, in this example we didn’t prefix the column names in the SELECT list with the alias. If we had done that, we would have seen the same error, but with a slightly different message:

SELECT 
    c.CatId,
    c.CatName
FROM Cats
INNER JOIN Dogs d
ON c.CatName = d.DogName;

Result:

ERROR 1054 (42S22): Unknown column 'c.CatId' in 'field list'

In this case, it detected the unknown columns in the field list before it found the one in the ON clause. Either way, the solution is the same.

Example 3

Here’s another example of code that produces the error:

SELECT 
    c.CatId,
    c.CatName
FROM Cats c
INNER JOIN Dogs d
ON Cats.CatName = d.DogName;

Result:

ERROR 1054 (42S22): Unknown column 'Cats.CatName' in 'on clause'

In this case, an alias was declared for the Cats table, but I didn’t use that alias in the ON clause.

The solution here, is to use the alias instead of the table name:

SELECT 
    c.CatId,
    c.CatName
FROM Cats c
INNER JOIN Dogs d
ON c.CatName = d.DogName;

MANAGED IT SERVICES — CLOUD SERVICES — CALL US +1 (855) 527-6627


By Tech-Assured     

January 27, 2021  26230 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…

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

Error: Code 1054. Unknown column 'U2.id_naslov' in 'field list' gets thrown on
this simple query in MySQL Workbench:

UPDATE krneki_1 AS U1, krneki_2 AS U2 
SET U1.id_naslov = U2.id_naslov
WHERE (U2.id_zaposlen = U1.id_naslovi_zaposleni)

I have searched and read other posts on the net but nothing helps…

I guess it’s a trivial solution but I just can’t see it.

This kind of error never came up on TSQL (sql server).

Table krneki_2 was created by Mysql workbench via data import (create new table) later on when this error occurred I also altered the number fields to smallint just to see if it helps… but… nothing.

Result of SHOW CREATE TABLE krneki_2:

       Table: krneki_2 
Create Table: CREATE TABLE `krneki_2` 
( `id` smallint(6) NOT NULL AUTO_INCREMENT, 
  `id_naslov` smallint(6) NOT NULL, 
  `id_zaposlen` smallint(6) NOT NULL, 
  PRIMARY KEY (id) 
) ENGINE=InnoDB AUTO_INCREMENT=204 DEFAULT CHARSET=utf8 

1 row in set (0.00 sec)

Result of SHOW CREATE TABLE krneki_1:

       Table: krneki_1
Create Table: CREATE TABLE `krneki_1` (
  `id_naslovi_zaposleni` smallint(6) NOT NULL AUTO_INCREMENT,
  `id_naslov` smallint(6) DEFAULT NULL,
  `id_zaposleni` smallint(6) DEFAULT NULL,
  `id_aktiven` tinyint(4) DEFAULT '0',
  `cas_vnosa` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id_naslovi_zaposleni`)
) ENGINE=InnoDB AUTO_INCREMENT=256 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

Results from information_schema, specifically from this query suggested in comments:

select
  table_catalog, table_schema, table_name, column_name, ordinal_position
from information_schema.columns
where table_name like '%krneki_1%' and column_name like '%naslov%' ;

Results for krneki_1 and naslov:

+---------------+--------------+-------------+----------------------+------------------+
| table_catalog | table_schema | table_name  | column_name          | ordinal_position |
+---------------+--------------+-------------+----------------------+------------------+
| def           | hq_db        | krneki_1    | id_naslovi_zaposleni |                1 |
| def           | hq_db        | krneki_1    | id_naslov            |                2 |
+---------------+--------------+-------------+----------------------+------------------+
2 rows in set (0.00 sec)

Results for krneki_2 and naslov:

+---------------+--------------+-------------+--------------+------------------+
| table_catalog | table_schema | table_name  | column_name  | ordinal_position |
+---------------+--------------+-------------+--------------+------------------+
| def           | hq_db        | krneki_2    | id_naslov    |                2 |
+---------------+--------------+-------------+--------------+------------------+
1 row in set (0.00 sec)

Results for krneki_2 and zaposlen:

+---------------+--------------+-------------+--------------+------------------+
| table_catalog | table_schema | table_name  | column_name  | ordinal_position |
+---------------+--------------+-------------+--------------+------------------+
| def           | hq_db        | krneki_2    | id_zaposlen  |                3 |
+---------------+--------------+-------------+--------------+------------------+
1 row in set (0.00 sec)

Further digging, as suggested:

select 
  table_catalog, table_schema, table_name, column_name, ordinal_position,         
  char_length(column_name) as cl, length(column_name) as l
from information_schema.columns 
where table_name = 'krneki_2' ;

Results for krneki_2:

+-------------+------------+----------+-----------+----------------+---+---+-------------+
|table_catalog|table_schema|table_name|column_name|ordinal_position| cl| l | column_type |
+-------------+------------+----------+-----------+----------------+---+---+-------------+
| def         | hq_db      | krneki_2 |id         |              1 |  2|  2| smallint(6) |
| def         | hq_db      | krneki_2 |id_naslov  |              2 | 10| 12| smallint(6) |
| def         | hq_db      | krneki_2 |id_zaposlen|              3 | 11| 11| smallint(6) |
+-------------+------------+----------+-----------+----------------+---+---+-------------+
3 rows in set (0.00 sec)

Results for krneki_1:

+-------------+------------+----------+--------------------+----------------+--+--+-----------+
|table_catalog|table_schema|table_name| column_name        |ordinal_position|cl| l|column_type|
+-------------+------------+----------+--------------------+----------------+--+--+-----------+
| def         | hq_db      | krneki_1 |id_naslovi_zaposleni|              1 |20|20|smallint(6)|
| def         | hq_db      | krneki_1 |id_naslov           |              2 | 9| 9|smallint(6)|
| def         | hq_db      | krneki_1 |id_zaposleni        |              3 |12|12|smallint(6)|
| def         | hq_db      | krneki_1 |id_aktiven          |              4 |10|10|tinyint(4) |
| def         | hq_db      | krneki_1 |cas_vnosa           |              5 | 9| 9|datetime   |
+-------------+------------+----------+--------------------+----------------+--+--+-----------+
5 rows in set (0.00 sec)

krneki_2 with HEX:

+-------------+------------+----------+-----------+----------------+--+--+-------------------------+
|table_catalog|table_schema|table_name|column_name|ordinal_position|cl|l | hex                     |      
+-------------+------------+----------+-----------+----------------+--+--+-------------------------+ 
| def         | hq_db      | krneki_2 |id         |              1 | 2| 2|6964                     |   
| def         | hq_db      | krneki_2 |id_naslov  |              2 |10|12|EFBBBF69645F6E61736C6F76 |   
| def         | hq_db      | krneki_2 |id_zaposlen|              3 |11|11|69645F7A61706F736C656E   |  
+-------------+------------+----------+-----------+----------------+--+--+-------------------------+   
3 rows in set (0.00 sec)  

krneki_1 with HEX:

+-------------+------------+----------+--------------------+----------------+--+--+----------------------------------------+
|table_catalog|table_schema|table_name|column_name         |ordinal_position|cl| l|hex                                     |              
+-------------+------------+----------+--------------------+----------------+--+--+----------------------------------------+
| def         | hq_db      | krneki_1 |id_naslovi_zaposleni|              1 |20|20|69645F6E61736C6F76695F7A61706F736C656E69|
| def         | hq_db      | krneki_1 |id_naslov           |              2 | 9| 9|69645F6E61736C6F76                      |
| def         | hq_db      | krneki_1 |id_zaposleni        |              3 |12|12|69645F7A61706F736C656E69                |
| def         | hq_db      | krneki_1 |id_aktiven          |              4 |10|10|69645F616B746976656E                    |
| def         | hq_db      | krneki_1 |cas_vnosa           |              5 | 9| 9|6361735F766E6F7361                      |
+-------------+------------+----------+--------------------+----------------+--+--+----------------------------------------+
5 rows in set (0.00 sec)

Joomla is a great way to create websites. It comes as free and requires zero expertise in coding too.

But, often due to bad configuration, Joomla reports error in the website. One such error is Joomla error 1054.

Usually, Joomla shows error 1054 when updating from older versions. And, often it makes Joomla backend unavailable.

That’s why, we often get requests from customers to fix Joomla errors as part of our Technical Support Services.

Today, we’ll see the details of error 1054 and how Bobcares’ Engineers fix it.

When, What and Why of Joomla error 1054 ?

Before proceeding further, we’ll see further details of error.

Usually, the 1054 error happens when upgrading Joomla to latest version from older version.

Recently, one of our customers reported this problem when doing an upgrade from 3.7.5 to 3.8. Unfortunately, the immediate effect is that Joomla back-end becomes inaccessible.  And, it reports variation of the error as:

Error 1054 Unknown column 'a.client_id' in 'where clause.'

Surprisingly, the Joomla frontend will work fine. Therefore, it affects customers only while make changes in the Joomla backend. When accessing the Joomla administrator panel, you do not see the usual control panel. Instead, it will show up as completely blank screen.

But, what causes the error?

Here, by this error, Joomla complains about missing columns in Joomla database. Just as site building tools like WordPress, Joomla also stores site configuration in Databases. And, error 1054 means problem with sites Joomla database.

How we fix error 1054 in Joomla?

Ok. The reason for error is screwed up database. Therefore, to make Joomla backend panel working again, we need to fix the database.

Again, fixing database errors need utmost care. We’ll now see how our Dedicated Engineers fix it for the customers.

1. From Joomla Admin panel

When Joomla admin panel is accessible, the error 1054 can be fixed from the panel itself.

For this, we follow the steps as listed below.

We select Extensions  Manage  Database from the drop-down menu of the Joomla! Administrator Panel. It will show errors with the Database. To fix them, our Support Engineers Click on the Fix button.
After a few seconds, it will show the “Database table structure is up to date” message:

That fixes the 1054 Unknown Column ‘client_id’ in ‘field list’ error and admin panel becomes accessible again.

2. From PHPMyAdmin

Unfortunately, in certain cases, Joomla admin panel just shows a blank page. In such cases, PHPMyAdmin helps in fixing database inconsistencies easily.  Luckily, running an SQL query in the database can solve the Joomla error.

That’s why, our Dedicated Engineers connect to the websites’ control panel and then to PHPMyAdmin.

We run the following SQL query commands to alter the database table.

ALTER TABLE `xxx_menu_types` ADD COLUMN `client_id` int(11) NOT NULL DEFAULT 0;

UPDATE `xxx_menu` SET `published` = 1 WHERE `menutype` = 'main' OR `menutype` = 'menu';

Here, we substitute ‘xxx’ with the prefix of website’s database tables:

After running this query, the Joomla panel becomes accessible again.

Conclusion

In short, Joomla error 1054 happens due to inconsistencies with website’s database. Today, we saw the details of the error and how our Dedicated Engineers fix it and make Joomla backend working again.

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

Let’s see when the #1054 error occurs in MySQL. While inserting a varchar value, if you will forget to add single quotes, then this error will arise.

Following is the error −

mysql> insert into DemoTable798 values(100,Adam);
ERROR 1054 (42S22): Unknown column 'Adam' in 'field list'

You need to use single quotes around the string value to fix this error as shown below −

mysql> insert into DemoTable798 values(100,’Adam’);

Let us first create a table −

mysql> create table DemoTable798 (
   StudentId int,
   StudentName varchar(100)
);
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable798 values(100,'Adam');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable798 values(101,'Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable798 values(102,'Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable798 values(103,'Carol');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable798;

This will produce the following output —

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 100       | Adam        |
| 101       | Chris       |
| 102       | Robert      |
| 103       | Carol       |
+-----------+-------------+
4 rows in set (0.00 sec)

Доброго времени суток. При выполнении запроса выдает ошибку [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

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


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

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

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

Ошибка вполне понятна, во внешнем 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…


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

09 февр. 2023, в 13:58

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

09 февр. 2023, в 13:28

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

09 февр. 2023, в 13:09

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

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

Понравилась статья? Поделить с друзьями:
  • Error 105 name not resolved the hostname could not be resolved как исправить
  • Error 105 name not resolved the hostname could not be resolved play machine
  • Error 105 name not resolved the host name could not be resolved
  • Error 105 left wheel short circuit
  • Error 105 insufficient free disk space on drive to back up