Where clause ошибка

I have a simple query:

SELECT u_name AS user_name FROM users WHERE user_name = "john";

I get Unknown Column 'user_name' in where clause. Can I not refer to 'user_name' in other parts of the statement even after select 'u_name as user_name'?

Btuman's user avatar

Btuman

8812 gold badges9 silver badges37 bronze badges

asked Sep 30, 2008 at 15:37

0

SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name has not yet occurred.

idmean's user avatar

idmean

14.5k9 gold badges54 silver badges83 bronze badges

answered Sep 30, 2008 at 15:41

dacracot's user avatar

dacracotdacracot

22k26 gold badges105 silver badges152 bronze badges

4

What about:

SELECT u_name AS user_name FROM users HAVING user_name = "john";

Marcus Adams's user avatar

Marcus Adams

53k9 gold badges93 silver badges143 bronze badges

answered Oct 4, 2010 at 15:03

Septimus's user avatar

SeptimusSeptimus

6495 silver badges3 bronze badges

2

See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html

«A select_expr can be given an alias
using AS alias_name. The alias is used
as the expression’s column name and
can be used in GROUP BY, ORDER BY, or
HAVING clauses.»

(…)

It is not permissible to refer to a column alias in a WHERE clause,
because the column value might not yet be determined when the WHERE
clause is executed. See Section B.5.4.4, “Problems with Column
Aliases”.

David Lopez's user avatar

answered Sep 30, 2008 at 15:44

Paul Dixon's user avatar

Paul DixonPaul Dixon

296k54 gold badges311 silver badges348 bronze badges

1

select u_name as user_name from users where u_name = "john";

Think of it like this, your where clause evaluates first, to determine which rows (or joined rows) need to be returned. Once the where clause is executed, the select clause runs for it.

To put it a better way, imagine this:

select distinct(u_name) as user_name from users where u_name = "john";

You can’t reference the first half without the second. Where always gets evaluated first, then the select clause.

answered Sep 30, 2008 at 15:41

Mark S.'s user avatar

Mark S.Mark S.

1,0821 gold badge12 silver badges22 bronze badges

If you’re trying to perform a query like the following (find all the nodes with at least one attachment) where you’ve used a SELECT statement to create a new field which doesn’t actually exist in the database, and try to use the alias for that result you’ll run into the same problem:

SELECT nodes.*, (SELECT (COUNT(*) FROM attachments 
WHERE attachments.nodeid = nodes.id) AS attachmentcount 
FROM nodes
WHERE attachmentcount > 0;

You’ll get an error «Unknown column ‘attachmentcount’ in WHERE clause».

Solution is actually fairly simple — just replace the alias with the statement which produces the alias, eg:

SELECT nodes.*, (SELECT (COUNT(*) FROM attachments 
WHERE attachments.nodeid = nodes.id) AS attachmentcount 
FROM nodes 
WHERE (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) > 0;

You’ll still get the alias returned, but now SQL shouldn’t bork at the unknown alias.

answered May 26, 2011 at 11:04

Jon's user avatar

JonJon

1211 silver badge2 bronze badges

5

Your defined alias are not welcomed by the WHERE clause you have to use the HAVING clause for this

SELECT u_name AS user_name FROM users HAVING user_name = "john";

OR you can directly use the original column name with the WHERE

SELECT u_name AS user_name FROM users WHERE u_name = "john";

Same as you have the result in user defined alias as a result of subquery or any calculation it will be accessed by the HAVING clause not by the WHERE

SELECT u_name AS user_name ,
(SELECT last_name FROM users2 WHERE id=users.id) as user_last_name
FROM users  WHERE u_name = "john" HAVING user_last_name ='smith'

answered Jul 30, 2013 at 17:28

M Khalid Junaid's user avatar

M Khalid JunaidM Khalid Junaid

63.9k10 gold badges90 silver badges118 bronze badges

Either:

SELECT u_name AS user_name
FROM   users
WHERE  u_name = "john";

or:

SELECT user_name
from
(
SELECT u_name AS user_name
FROM   users
)
WHERE  u_name = "john";

The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view.

answered Sep 30, 2008 at 15:41

David Aldridge's user avatar

David AldridgeDavid Aldridge

51.5k8 gold badges69 silver badges96 bronze badges

corrected:

SELECT u_name AS user_name FROM users WHERE u_name = 'john';

answered Sep 30, 2008 at 15:39

Steven A. Lowe's user avatar

Steven A. LoweSteven A. Lowe

60.3k18 gold badges133 silver badges202 bronze badges

No you need to select it with correct name. If you gave the table you select from an alias you can use that though.

answered Sep 30, 2008 at 15:38

Per Hornshøj-Schierbeck's user avatar

No you cannot. user_name is doesn’t exist until return time.

answered Sep 30, 2008 at 15:38

Jarrett Meyer's user avatar

Jarrett MeyerJarrett Meyer

19.3k6 gold badges59 silver badges52 bronze badges

SELECT user_name
FROM
(
SELECT name AS user_name
FROM   users
) AS test
WHERE  user_name = "john"

Jason Plank's user avatar

Jason Plank

2,3365 gold badges31 silver badges40 bronze badges

answered Apr 23, 2009 at 8:44

1

Unknown column in WHERE clause caused by lines 1 and 2 and resolved by line 3:

  1. $sql = "SELECT * FROM users WHERE username =".$userName;
  2. $sql = "SELECT * FROM users WHERE username =".$userName."";
  3. $sql = "SELECT * FROM users WHERE username ='".$userName."'";

Jason Plank's user avatar

Jason Plank

2,3365 gold badges31 silver badges40 bronze badges

answered Jan 28, 2010 at 23:06

oliyide's user avatar

1

May be it helps.

You can

SET @somevar := '';
SELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = "john";

It works.

BUT MAKE SURE WHAT YOU DO!

  • Indexes are NOT USED here
  • There will be scanned FULL TABLE — you hasn’t specified the LIMIT 1 part
  • So, — THIS QUERY WILL BE SLLLOOOOOOW on huge tables.

But, may be it helps in some cases

answered Nov 22, 2011 at 10:59

F_S's user avatar

While you can alias your tables within your query (i.e., «SELECT u.username FROM users u;»), you have to use the actual names of the columns you’re referencing. AS only impacts how the fields are returned.

answered Sep 30, 2008 at 15:41

Blumer's user avatar

BlumerBlumer

5,0052 gold badges34 silver badges47 bronze badges

1

Just had this problem.

Make sure there is no space in the name of the entity in the database.

e.g. ‘ user_name’ instead of ‘user_name’

answered Apr 2, 2015 at 15:15

user3103155's user avatar

0

I had the same problem, I found this useful.

mysql_query("SELECT * FROM `users` WHERE `user_name`='$user'");

remember to put $user in ‘ ‘ single quotes.

answered Jan 5, 2013 at 10:05

devWaleed's user avatar

devWaleeddevWaleed

4753 silver badges14 bronze badges

1

Здраствуйте. Изучаю php и mysql (пока новичок). Решил проверить свои знания на практике! Сделаю тестовый сайт: Все было хорошо, ПОКА не сталковалась с праблемой Unknown column ‘POP’ in ‘where clause’. Поискал решение в интернете, нашел что-ты www.cyberforum.ru/php-beginners/thread566531.html. Не помогал!: Поискал дальше, но нечего подобного не нашел. Решил написать здесь.


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

  • 2203 просмотра

Mysql пишет: «я не знаю POP в (where) поле clause«
т.е. вы делаете запрос в БД где хотите выбрать в поле clause значения, которые (равны) называются POP
и он пишет: sorry I dont know wtf is POP
напишите пример запроса сюда (запроса в БД)
п.с. для всех — кто в будущем планирует задавать аналогичные вопросы: сразу в теле вопроса пишите свой код (часть кода, где появляется ошибка) и код вставляйте сюда:
4b36892d9f5b479f86d4dce4f3ca6c8a.PNGОТВЕТ

$sql = "SELECT * FROM section_song WHERE section='".$category."'";

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

Когда значение = цифру, все прекрасна работает!


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

21 сент. 2023, в 20:54

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

21 сент. 2023, в 20:40

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

21 сент. 2023, в 19:28

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

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

I have a simple query:

SELECT u_name AS user_name FROM users WHERE user_name = "john";

I get Unknown Column 'user_name' in where clause. Can I not refer to 'user_name' in other parts of the statement even after select 'u_name as user_name'?

Btuman's user avatar

Btuman

8812 gold badges9 silver badges37 bronze badges

asked Sep 30, 2008 at 15:37

0

SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name has not yet occurred.

idmean's user avatar

idmean

14.5k9 gold badges54 silver badges83 bronze badges

answered Sep 30, 2008 at 15:41

dacracot's user avatar

dacracotdacracot

22k26 gold badges105 silver badges152 bronze badges

4

What about:

SELECT u_name AS user_name FROM users HAVING user_name = "john";

Marcus Adams's user avatar

Marcus Adams

53k9 gold badges93 silver badges143 bronze badges

answered Oct 4, 2010 at 15:03

Septimus's user avatar

SeptimusSeptimus

6495 silver badges3 bronze badges

2

See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html

«A select_expr can be given an alias
using AS alias_name. The alias is used
as the expression’s column name and
can be used in GROUP BY, ORDER BY, or
HAVING clauses.»

(…)

It is not permissible to refer to a column alias in a WHERE clause,
because the column value might not yet be determined when the WHERE
clause is executed. See Section B.5.4.4, “Problems with Column
Aliases”.

David Lopez's user avatar

answered Sep 30, 2008 at 15:44

Paul Dixon's user avatar

Paul DixonPaul Dixon

296k54 gold badges311 silver badges348 bronze badges

1

select u_name as user_name from users where u_name = "john";

Think of it like this, your where clause evaluates first, to determine which rows (or joined rows) need to be returned. Once the where clause is executed, the select clause runs for it.

To put it a better way, imagine this:

select distinct(u_name) as user_name from users where u_name = "john";

You can’t reference the first half without the second. Where always gets evaluated first, then the select clause.

answered Sep 30, 2008 at 15:41

Mark S.'s user avatar

Mark S.Mark S.

1,0821 gold badge12 silver badges22 bronze badges

If you’re trying to perform a query like the following (find all the nodes with at least one attachment) where you’ve used a SELECT statement to create a new field which doesn’t actually exist in the database, and try to use the alias for that result you’ll run into the same problem:

SELECT nodes.*, (SELECT (COUNT(*) FROM attachments 
WHERE attachments.nodeid = nodes.id) AS attachmentcount 
FROM nodes
WHERE attachmentcount > 0;

You’ll get an error «Unknown column ‘attachmentcount’ in WHERE clause».

Solution is actually fairly simple — just replace the alias with the statement which produces the alias, eg:

SELECT nodes.*, (SELECT (COUNT(*) FROM attachments 
WHERE attachments.nodeid = nodes.id) AS attachmentcount 
FROM nodes 
WHERE (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) > 0;

You’ll still get the alias returned, but now SQL shouldn’t bork at the unknown alias.

answered May 26, 2011 at 11:04

Jon's user avatar

JonJon

1211 silver badge2 bronze badges

5

Your defined alias are not welcomed by the WHERE clause you have to use the HAVING clause for this

SELECT u_name AS user_name FROM users HAVING user_name = "john";

OR you can directly use the original column name with the WHERE

SELECT u_name AS user_name FROM users WHERE u_name = "john";

Same as you have the result in user defined alias as a result of subquery or any calculation it will be accessed by the HAVING clause not by the WHERE

SELECT u_name AS user_name ,
(SELECT last_name FROM users2 WHERE id=users.id) as user_last_name
FROM users  WHERE u_name = "john" HAVING user_last_name ='smith'

answered Jul 30, 2013 at 17:28

M Khalid Junaid's user avatar

M Khalid JunaidM Khalid Junaid

63.9k10 gold badges90 silver badges118 bronze badges

Either:

SELECT u_name AS user_name
FROM   users
WHERE  u_name = "john";

or:

SELECT user_name
from
(
SELECT u_name AS user_name
FROM   users
)
WHERE  u_name = "john";

The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view.

answered Sep 30, 2008 at 15:41

David Aldridge's user avatar

David AldridgeDavid Aldridge

51.5k8 gold badges69 silver badges96 bronze badges

corrected:

SELECT u_name AS user_name FROM users WHERE u_name = 'john';

answered Sep 30, 2008 at 15:39

Steven A. Lowe's user avatar

Steven A. LoweSteven A. Lowe

60.3k18 gold badges133 silver badges202 bronze badges

No you need to select it with correct name. If you gave the table you select from an alias you can use that though.

answered Sep 30, 2008 at 15:38

Per Hornshøj-Schierbeck's user avatar

No you cannot. user_name is doesn’t exist until return time.

answered Sep 30, 2008 at 15:38

Jarrett Meyer's user avatar

Jarrett MeyerJarrett Meyer

19.3k6 gold badges59 silver badges52 bronze badges

SELECT user_name
FROM
(
SELECT name AS user_name
FROM   users
) AS test
WHERE  user_name = "john"

Jason Plank's user avatar

Jason Plank

2,3365 gold badges31 silver badges40 bronze badges

answered Apr 23, 2009 at 8:44

1

Unknown column in WHERE clause caused by lines 1 and 2 and resolved by line 3:

  1. $sql = "SELECT * FROM users WHERE username =".$userName;
  2. $sql = "SELECT * FROM users WHERE username =".$userName."";
  3. $sql = "SELECT * FROM users WHERE username ='".$userName."'";

Jason Plank's user avatar

Jason Plank

2,3365 gold badges31 silver badges40 bronze badges

answered Jan 28, 2010 at 23:06

oliyide's user avatar

1

May be it helps.

You can

SET @somevar := '';
SELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = "john";

It works.

BUT MAKE SURE WHAT YOU DO!

  • Indexes are NOT USED here
  • There will be scanned FULL TABLE — you hasn’t specified the LIMIT 1 part
  • So, — THIS QUERY WILL BE SLLLOOOOOOW on huge tables.

But, may be it helps in some cases

answered Nov 22, 2011 at 10:59

F_S's user avatar

While you can alias your tables within your query (i.e., «SELECT u.username FROM users u;»), you have to use the actual names of the columns you’re referencing. AS only impacts how the fields are returned.

answered Sep 30, 2008 at 15:41

Blumer's user avatar

BlumerBlumer

5,0052 gold badges34 silver badges47 bronze badges

1

Just had this problem.

Make sure there is no space in the name of the entity in the database.

e.g. ‘ user_name’ instead of ‘user_name’

answered Apr 2, 2015 at 15:15

user3103155's user avatar

0

I had the same problem, I found this useful.

mysql_query("SELECT * FROM `users` WHERE `user_name`='$user'");

remember to put $user in ‘ ‘ single quotes.

answered Jan 5, 2013 at 10:05

devWaleed's user avatar

devWaleeddevWaleed

4753 silver badges14 bronze badges

1

При использовании ряда 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 working with programs that pull data from databases, you may occasionally run across different types of errors. Many of them are fixable, specifically if you are coding your own SQL queries. This article describes the ‘1052 Column in where clause is ambiguous‘ error and how to correct it.

The Error

This type of error occurs when a SQL query is working with more than one table. Our example below is using two tables within an ecommerce program and generates the following error:

Notice: Error: Column ‘firstname’ in where clause is ambiguous
Error No: 1052
SELECT COUNT(*) AS total FROM oc_customer c LEFT JOIN oc_address a ON (c.customer_id = a.customer_id) WHERE CONCAT(firstname, ‘ ‘, lastname) LIKE ‘%john%’

What causes the error

The query gives each table an alias, the oc_customer table gets an alias of c and the oc_address table gets an alias of a. This is used to define which table the column is supposed to come from, such as the section of the query c.customer_id = a.customer_id. This is the same as saying oc_customer.customer_id = oc_address.customer_id. There is another section that has column names but the script fails to identify which table to look into, CONCAT(firstname, ‘ ‘, lastname). Since both the oc_customer and oc_address tables have columns named firstname and lastname, the server does not know which table to work with, and thus throws the error.

Fixing the error

To fix this, simply add the tablename or alias for the table you want to work with. If you are writing the query yourself, this is a bit easier to deal with as you will know which table you meant to use. In our example, we should add the alias for the oc_customer table, c, to the column names. Our code snippet would look like this: CONCAT(c.firstname, ‘ ‘, c.lastname) making the whole query appear as below.

SELECT COUNT(*) AS total FROM oc_customer c LEFT JOIN oc_address a ON (c.customer_id = a.customer_id) WHERE CONCAT(c.firstname, ‘ ‘, c.lastname) LIKE ‘%john%’

If you are working with a developer or a professional level program (open source or purchased) you will need to let them know of the error. They will be able to fix the issue in their next release.

The query will now run correctly as it knows which table to work with on all columns.

Понравилась статья? Поделить с друзьями:
  • Whea logger 18 произошла неустранимая аппаратная ошибка
  • When was invented the bicycle где ошибка
  • Wheelman ошибка неправильная конфигурация
  • Whea ошибка occt память
  • Whea logger 47 устранимая аппаратная ошибка память