Why I get #1060 — Duplicate column name ‘id’
SELECT COUNT(*) FROM (SELECT * FROM `tips` `t` LEFT JOIN
tip_usage ON tip_usage.tip_id=t.id GROUP BY t.id) sq
OMG Ponies
326k82 gold badges523 silver badges502 bronze badges
asked Jan 27, 2011 at 11:16
Pentium10Pentium10
205k122 gold badges423 silver badges502 bronze badges
5
Probably because the * in select *
selects two columns with the same name from tip_usage
and tips
.
answered Jan 27, 2011 at 11:21
1
Probably it’s because the inner select yields two columns with the name id
. Since you are not using those columns, you can just change the select to:
SELECT COUNT(*) FROM (SELECT t.id FROM `tips` `t`
LEFT JOIN tip_usage ON tip_usage.tip_id=t.id
GROUP BY t.id) sq
answered Jan 27, 2011 at 11:21
0
Your query is equivalent to this:
SELECT COUNT(DISTINCT id)
FROM tips
, there is no need in a join.
Are you sure you didn’t want an INNER JOIN
instead?
answered Jan 27, 2011 at 11:23
QuassnoiQuassnoi
414k91 gold badges617 silver badges614 bronze badges
Had the same problem, renaming into select clause saved me
SELECT people.id, vehicle.id ...
I renamed it with AS keyword
SELECT people.id AS person_id, vehicle.id ...
answered Jul 4, 2018 at 1:34
PipoPipo
4,68138 silver badges47 bronze badges
Why I get #1060 — Duplicate column name ‘id’
SELECT COUNT(*) FROM (SELECT * FROM `tips` `t` LEFT JOIN
tip_usage ON tip_usage.tip_id=t.id GROUP BY t.id) sq
OMG Ponies
326k82 gold badges523 silver badges502 bronze badges
asked Jan 27, 2011 at 11:16
Pentium10Pentium10
205k122 gold badges423 silver badges502 bronze badges
5
Probably because the * in select *
selects two columns with the same name from tip_usage
and tips
.
answered Jan 27, 2011 at 11:21
1
Probably it’s because the inner select yields two columns with the name id
. Since you are not using those columns, you can just change the select to:
SELECT COUNT(*) FROM (SELECT t.id FROM `tips` `t`
LEFT JOIN tip_usage ON tip_usage.tip_id=t.id
GROUP BY t.id) sq
answered Jan 27, 2011 at 11:21
0
Your query is equivalent to this:
SELECT COUNT(DISTINCT id)
FROM tips
, there is no need in a join.
Are you sure you didn’t want an INNER JOIN
instead?
answered Jan 27, 2011 at 11:23
QuassnoiQuassnoi
414k91 gold badges617 silver badges614 bronze badges
Had the same problem, renaming into select clause saved me
SELECT people.id, vehicle.id ...
I renamed it with AS keyword
SELECT people.id AS person_id, vehicle.id ...
answered Jul 4, 2018 at 1:34
PipoPipo
4,68138 silver badges47 bronze badges
Ошибка под номером 1060, появляющаяся в MySQL при определенном SQL запросе к Базе Данных означает, что в таблицах БД уже существуют колонки таблиц, которые пытаются установить.
В Joomla эта ошибка появляется при попытке обновить или установить повторно, какое либо, расширение. Ошибка не сложная, и она означает, что в БД уже есть такая колонка, которую пытаются установить. Инсталлятор Joomla подробно расшифрует ее в информационной розовой строке.
Инсталлятор покажет, какой SQL запрос вызвал ошибку и покажет название колонки, которая дублируется.
Этот скриншот не относится к примеру в статье, но относиться к ошибке #1060
Error-SQL-DB-1060-foto3
Исправление ошибки 1060 Error SQL DB
Для исправления ошибки авторизуемся в панели управления на своем сервере, входим в phpMyAdmin и открываем базу данных своего сайта.
Важно! Сделайте резервную копию базы данных. Кнопка «Экспорт», выбрать все таблицы, сжатие ZIP или gZIP. В случае ошибки можно восстановить БД (кнопка «Импорт»).
Для дополнительной проверки инсталлятора Joomla делаем в базу данных запрос, который привел к ошибке и вы видите его в информационной строке инсталлятора.
Error-SQL-DB-1060-foto1
Получаем ответ, от MySQL. В моем примере я обновлял компонент ARTIO JoomSEF. Запрос вы видите на фото, как в принципе и ответ MySQL: #1060-dublicate column name ‘metecustom’. В запросе видим название таблицы: sefurls. В ответе видим, что колонка ‘metecustom’ уже есть в базе данных.
Дальше не сложно. Открываете таблицу sefurls (кликаете по названию в левом списке таблиц), ищите колонку ‘metecustom’. Это текстовая колонка без данных. Далее, удаляем эту колонку, нажав на красный крест в ее строке. Или выделяем чекбокс колонки и нажимаем кнопку «Удалить» в фильтре «Действия» внизу таблицы.
Error-SQL-DB-1060-foto2
Возвращаемся в административную часть сайта и устанавливаем расширение заново. Должно все получиться.
Причина ошибки MySQL #1060
Откуда появляется ошибка дублирования колонок. В моем примере эта ошибка появилась из-за того, что я в ручную переносил базу данных ARTIO JoomSEF при обновлении Joomla1.5 до Joomla2.5. В работе это не мешало, а вот при обновлении расширения проявилось. В любом случае, Ошибка MySQL, #1060 Error SQL DB на CMS Joomla не сложная, просто внимательно читайте сообщение JInstaller (инсталлятора Joomla).
©Joomla-abc.ru
Другие ошибки Joomla
Что такое логи сайта
Что такое логи сайта
Логи это специальные текстовые файлы с записями всех обращений к сайту. Каж…
Why I get #1060 — Duplicate column name ‘id’
SELECT COUNT(*) FROM (SELECT * FROM `tips` `t` LEFT JOIN
tip_usage ON tip_usage.tip_id=t.id GROUP BY t.id) sq
OMG Ponies
324k80 gold badges520 silver badges499 bronze badges
asked Jan 27, 2011 at 11:16
Pentium10Pentium10
204k122 gold badges422 silver badges500 bronze badges
5
Probably because the * in select *
selects two columns with the same name from tip_usage
and tips
.
answered Jan 27, 2011 at 11:21
1
Probably it’s because the inner select yields two columns with the name id
. Since you are not using those columns, you can just change the select to:
SELECT COUNT(*) FROM (SELECT t.id FROM `tips` `t`
LEFT JOIN tip_usage ON tip_usage.tip_id=t.id
GROUP BY t.id) sq
answered Jan 27, 2011 at 11:21
0
Your query is equivalent to this:
SELECT COUNT(DISTINCT id)
FROM tips
, there is no need in a join.
Are you sure you didn’t want an INNER JOIN
instead?
answered Jan 27, 2011 at 11:23
QuassnoiQuassnoi
411k91 gold badges613 silver badges613 bronze badges
Had the same problem, renaming into select clause saved me
SELECT people.id, vehicle.id ...
I renamed it with AS keyword
SELECT people.id AS person_id, vehicle.id ...
answered Jul 4, 2018 at 1:34
PipoPipo
4,57338 silver badges47 bronze badges
От автора
Ошибка под номером 1060, появляющаяся в MySQL при определенном SQL запросе к Базе Данных означает, что в таблицах БД уже существуют колонки таблиц, которые пытаются установить.
В Joomla эта ошибка появляется при попытке обновить или установить повторно, какое либо, расширение. Ошибка не сложная, и она означает, что в БД уже есть такая колонка, которую пытаются установить. Инсталлятор Joomla подробно расшифрует ее в информационной розовой строке.
Инсталлятор покажет, какой SQL запрос вызвал ошибку и покажет название колонки, которая дублируется.
Этот скриншот не относится к примеру в статье, но относиться к ошибке #1060
Исправление ошибки 1060 Error SQL DB
Для исправления ошибки авторизуемся в панели управления на своем сервере, входим в phpMyAdmin и открываем базу данных своего сайта.
Важно! Сделайте резервную копию базы данных. Кнопка «Экспорт», выбрать все таблицы, сжатие ZIP или gZIP. В случае ошибки можно восстановить БД (кнопка «Импорт»).
Для дополнительной проверки инсталлятора Joomla делаем в базу данных запрос, который привел к ошибке и который вы видите в информационной строке инсталлятора.
Получаем ответ, от MySQL. В моем примере я обновлял компонент ARTIO JoomSEF. Запрос вы видите на фото, как в принципе и ответ MySQL: #1060-dublicate column name ‘metecustom’. В запросе видим название таблицы: sefurls. В ответе видим, что колонка ‘metecustom’ уже есть в базе данных.
Дальше не сложно. Открываете таблицу sefurls (кликаете по названию в левом списке таблиц), ищите колонку ‘metecustom’. Это текстовая колонка без данных. Далее, удаляем эту колонку, нажав на красный крест в ее строке. Или выделяем чекбокс колонки и нажимаем кнопку «Удалить» в фильтре «Действия» внизу таблицы.
Возвращаемся в административную часть сайта и устанавливаем расширение заново. Должно все получиться.
Откуда появляется ошибка дублирования колонок. В моем примере эта ошибка появилась из-за того, что я в ручную переносил базу данных ARTIO JoomSEF при обновлении Joomla1.5 до Joomla2.5. В работе это не мешало, а вот при обновлении расширения проявилось. В любом случае, Ошибка MySQL, #1060 Error SQL DB на CMS Joomla не сложная, просто внимательно читайте сообщение JInstaller (инсталлятора Joomla).
©Joomla-abc.ru
Другие ошибки Joomla
You can do this in MySQL (and other standard databases) by using the using
form of the join
instead of the on
clause.
Unfortunately, you can do that here because the join keys have different ids in the two tables. If they had the same name, you would just do:
CREATE VIEW VIEW_CAMPAIGNS AS
SELECT *,
FROM campaigns c join
advertisers a
using (advertisers_id);
The nearest you can do is to choose the bigger table, use *
for that and then list all the columns for the other table.
Or, better yet, just use the information_schame.columns
table to generate the column names. Something like:
select (case when column_name = 'id' and table_name = 'campaigns' then `c.campaign_id`
when column_name = 'id' and table_name = 'advertisers' then 'a.advertiser_id'
when table_name = 'campaigns' then concat('c.', column_name)
when table_name = 'advertisers' then concat('a.', column_name)
end) as column_name
from information_schema.columns
where table_name in ('campaigns, 'advertisers')
делаю запрос
SELECT COUNT(*)
FROM (
SELECT
`fl_serial`.`id`,
`fl_serial`.`name_serial`,
`fl_serial`.`slug_serial`,
`fl_serial`.`description_serial`,
`fl_serial`.`nesting`,
`fl_serial`.`year`,
`fl_serial`.`country_title`,
`fl_film`.`id`,
`fl_film`.`name_film`,
`fl_film`.`slug_film`,
`fl_film`.`description_film`,
`fl_film`.`nesting`,
`fl_film`.`year`,
`fl_film`.`country_title`,
`fl_mfilm`.`id`,
`fl_mfilm`.`name_mfilm`,
`fl_mfilm`.`slug_mfilm`,
`fl_mfilm`.`description_mfilm`,
`fl_mfilm`.`nesting`,
`fl_mfilm`.`year`,
`fl_mfilm`.`country_title`,
`fl_cat_serial`.`id`,
COALESCE(`fl_serial`.`id`, `fl_film`.`id`, `fl_mfilm`.`id` ) AS `ids`,
COALESCE(`fl_serial`.`name_serial`, `fl_film`.`name_film`, `fl_mfilm`.`name_mfilm` ) AS `name`,
COALESCE(`fl_serial`.`slug_serial`, `fl_film`.`slug_film`, `fl_mfilm`.`slug_mfilm`) AS `slug`,
COALESCE(`fl_serial`.`description_serial`, `fl_film`.`description_film`, `fl_mfilm`.`description_mfilm`) AS `description`,
COALESCE(`fl_serial`.`nesting`, `fl_film`.`nesting`, `fl_mfilm`.`nesting` ) AS `nesting`,
COALESCE(`fl_serial`.`year`, `fl_film`.`year`, `fl_mfilm`.`year` ) AS `years`,
COALESCE(`fl_serial`.`country_title`, `fl_film`.`country_title`, `fl_mfilm`.`country_title` ) AS `country_title`
FROM `fl_cat_serial`
LEFT JOIN `fl_serial` ON fl_cat_serial.id_serial = fl_serial.id
LEFT JOIN `fl_film` ON fl_cat_serial.id_film = fl_film.id
LEFT JOIN `fl_mfilm` ON fl_cat_serial.id_mfilm = fl_mfilm.id
WHERE `fl_cat_serial`.`id_cat`=12
GROUP BY `ids`) `c`
получаю следующую ошибку
#1060 — Duplicate column name ‘id’
почему ? И как исправить ?
-
-
-
- ERROR 1060
- Dos client garbled problem
- ERROR 1395 :Can not delete from join view
- column ‘**’ in field list is ambiguous
-
-
ERROR 1060
1. Error description:
Duplicate column name ‘xxx’;
Duplicate field xxx. When adding a database field, adding an existing field in the database will report this error
2. Example demonstration:
# The table structure is as follows
select * from dept;
+--------+----------+
| deptId | deptName |
+--------+----------+
| 1 | Development Department |
| 2 | Test Department |
| 3 | UI Department |
| 4 | Game Department |
+--------+----------+
#Add a field named deptId on the original table structure
alter table dept add deptId bigint(20);
#Error, suggesting that the deptId field is repeated
ERROR 1060 (42S21): Duplicate column name 'deptId'
Dos client garbled problem
1. Problem description:
When using cmd to open MySQL on Windows, garbled characters appear. After checking the database encoding, the encoding is utf8; the reason for this error is because the operating system is a Chinese operating system, and the default character set is GB2312 , But the character encoding used when displaying Chinese in the MySQL client output window is utf8
View the character encoding used in the output window
show variables like 'char%';
2. Solution
Change the encoding of the output console to gb2312
set character_set_results=gb2312;
Display after changing encoding
Note: If you use the mysql client tool, this error will not occur
ERROR 1395 :Can not delete from join view
1. Error description
Multiple tables use internal connections to generate a view, try to delete a record from this view, this error occurs
#Create a view
create view view_emp_all
as
select d.deptId,d.deptName,e.empName,e.salary,e.phone
from
dept d inner join emp e on d.deptId=e.deptId;
#View view
select * from view_emp_all;
+--------+----------+---------+--------+-------+
| deptId | deptName | empName | salary | phone |
+--------+----------+---------+--------+-------+
| 1 | Development Department | Zhang San | 10000 | 111 |
| 1 | Development Department | Li Si | 9999 | 112 |
| 2 | Test Department | Wang Wu | 8888 | 113 |
3 | UI Department | Zhao Liu | 7777 | 114 |
+--------+----------+---------+--------+-------+
Delete the record with deptId=1 in view_emp_all
delete from view_emp_all where deptId=1;
ERROR 1395 (HY000): Can not delete from join view 'test55.view_emp_all'
2. Solution
The first case: check whether the view can be modified, only the view can be modified to delete
#Check if the view is updatable
SELECT IS_UPDATABLE FROM information_schema.views WHERE TABLE_NAME = 'view_emp_all';
#Check whether all views in the test55 database can be updated
SELECT table_name,is_updatable FROM information_schema.views WHERE table_schema = 'test55';
+--------------+
| IS_UPDATABLE |
+--------------+
| YES |
+--------------+
The second case: the view created by the connection query, the delete operation may not only change the records in a table, the database will not allow this to ensure the integrity of the data, so you can only step by step from the table that builds this view Delete the record to delete the view record to be deleted
column ‘**’ in field list is ambiguous
1. Description:
When querying the contingency table, it is not specified which table the field belongs to, resulting in ambiguity
2. Examples
The first table contains the studentId field
select studentId,studentName from student;
+-----------+-------------+
| studentId | studentName |
+-----------+-------------+
| 16046122 | Zhang San |
| 16046124 | Li Si |
| 16045122 | Wang Wu |
| 16045123 | Zhao Liu |
+-----------+-------------+
The second table also contains the studentId field
select studentId from truant;
+-----------+
| studentId |
+-----------+
| 16046122 |
| 16046124 |
+-----------+
You can see that the table to which the student belongs was not specified during the query, and ambiguity occurred at this time
Solution, declare which table the field belongs to
select student.studentId,studentName from student inner join truant where student.studentId=truant.studentId;
+-----------+-------------+
| studentId | studentName |
+-----------+-------------+
| 16046122 | Zhang San |
| 16046124 | Li Si |
+-----------+-------------+
Table of Contents
- 1 Why is MySQL error 1060 ” duplicate column name ” thrown?
- 2 How to rename a column in MySQL with ALTER TABLE?
- 3 How to fix duplicate column name using views?
- 4 Can a SELECT query return two columns with the same name?
OK. The MySQL error 1060 “duplicate column name” is thrown. Duplicate column name ‘name’ The offending columns are c.`name` and p.`name`. If c.`website` is substituted in the select for c.`name`, the view can be created. This duplicate column name error should not be thrown if the duplicate column names are in different tables. Correct?
Why is MySQL error 1060 error 42s21?
When I do the selection with left join syntax on these three tables, I got the error:- ERROR 1060 (42S21): Duplicate column name ‘AI0_HV’ At first, no problem with two tables till I add more syntax for three tables.
How to rename a column in MySQL with ALTER TABLE?
Rename MySQL Column with ALTER TABLE Command ALTER TABLE is an essential command used to change the structure of a MySQL table. You can use it to add or delete columns, change the type of data within the columns, and even rename entire databases. The function that concerns us the most is how to utilize ALTER TABLE to rename a column.
Are there any tables with similiar column names?
There are three table (with different names) with similiar column names. When I do the selection with left join syntax on these three tables, I got the error:- ERROR 1060 (42S21): Duplicate column name ‘AI0_HV’ At first, no problem with two tables till I add more syntax for three tables.
OK. The MySQL error 1060 “duplicate column name” is thrown. Duplicate column name ‘name’ The offending columns are c.`name` and p.`name`. If c.`website` is substituted in the select for c.`name`, the view can be created. This duplicate column name error should not be thrown if the duplicate column names are in different tables. Correct?
How to fix duplicate column name using views?
The error crops up when we use the query as a view (either an inline view, or a stored view.) The workaround is to rename the columns by providing a column alias, so that no two columns in the resultset have the same name. For example:
Is there only one title column in MySQL?
I found this thread on a 1060 error But wasn’t able to figure out how that applied to my situation. I’ve checked the table and as far as I can tell there is only one ‘title’ column, so I can’t figure out what is happening- any ideas? I’m using MySQL 4.1.9 Thanks.
Can a SELECT query return two columns with the same name?
The SELECT query is probably valid, but it does return columns that have the same name. Two columns with the name first_name, and two columns named last_name. The error crops up when we use the query as a view (either an inline view, or a stored view.)