Ошибка 1066 mysql

Your error is because you have:

     JOIN user ON article.author_id = user.id
LEFT JOIN user ON article.modified_by = user.id

You have two instances of the same table, but the database can’t determine which is which. To fix this, you need to use table aliases:

     JOIN USER u ON article.author_id = u.id
LEFT JOIN USER u2 ON article.modified_by = u2.id

It’s good habit to always alias your tables, unless you like writing the full table name all the time when you don’t have situations like these.

The next issues to address will be:

SELECT article.* , section.title, category.title, user.name, user.name

1) Never use SELECT * — always spell out the columns you want, even if it is the entire table. Read this SO Question to understand why.

2) You’ll get ambiguous column errors relating to the user.name columns because again, the database can’t tell which table instance to pull data from. Using table aliases fixes the issue:

SELECT article.* , section.title, category.title, u.name, u2.name

Not unique table/alias is an SQL error message that shows up on the screen if you don’t have the correct SQL join statement. It happens in lots of applications, and this article has selected the top five to teach you why it happens and how to fix it.Not Unique Table Alias

Our teaching approach will show you how you can be a better SQL developer and use SQL applications like SQL servers and MySQL. To follow along, grab your computer, and let’s fix the unique table/alias error in your SQL code.

Contents

  • Why Do Your SQL Statements Have No Unique Table or Aliases?
    • – There Is No Alias in Your SQL Statement
    • – You Joined a Table to Itself
    • – Two Tables Have the Same Name and Lower_case_table_names=1
    • – Your Code Has Duplicate Aliases or Models
  • How Your SQL Statements Can Have Unique Tables and Aliases?
    • – Use an Alias When You’re Joining Tables
    • – Don’t Join the Same Table
    • – Rename Your Tables Before a Database Dump
    • – Assign Unique Aliases to Models in Typeorm
    • – Assign Aliases to Associations or Relationships
  • Conclusion

Why Do Your SQL Statements Have No Unique Table or Aliases?

Your SQL statements have no unique table or aliases because of the following:

  • There is no alias in your SQL statement
  • You joined a table to itself
  • Two tables have the same name and lower_case_table_names=1
  • Your code has duplicate aliases or models

– There Is No Alias in Your SQL Statement

Different tables in your database can have columns with the same name. When you’re joining these tables using a SELECT statement, a conflict can occur that leads to the “unique” error. For example, the following SQL join statement will lead to the following error message when you run it: error code: 1066. not unique table/alias:

SELECT tech_articles.* , article_sections.title, article_categories.title, account_users.name, account_users.name

FROM tech_articles

INNER JOIN article_sections ON tech_articles.section_id = article_sections.id

INNER JOIN article_categories ON tech_articles.category_id = article_categories.id

INNER JOIN account_users ON tech_articles.author_id = account_users.id

LEFT JOIN account_users ON tech_articles.modified_by = account_users.id

WHERE tech_articles.id = ‘1’

This error occurred because the SELECT statement called “account_users” twice from the “tech_articles” table. Also, the following is a similar example that causes the “mysql update not unique table/alias” error. The same will happen if you don’t use table aliases in your Laravel controller, and it will also lead to the “not unique table/alias laravel” error.

SELECT software_projects.sp_ID, sp_Title, engineers_account.ea_ID, uName, access_Level

FROM software_projects

JOIN engineers_account

ON software_projects.AccountID = engineers_account.ea_ID

JOIN Project

ON software_projects.sp_ID = Project.Project_ID

where access_Level = ‘Client’;

– You Joined a Table to Itself

In SQL, you don’t join a table to itself because it can lead to errors like the MySQL not unique table/alias join error. This type of error arises as a result of typographical errors. For example, the following SQL joins the “Shares” table to itself using a “LEFT JOIN”.

SELECT Shares.share_price, InvestorsShares.share_id, InvestorsShares.Quantity

FROM Shares

LEFT JOIN Shares on Shares.share_id = InvestorsShares.share_id

WHERE Shares.share_id = <random_number />

A similar error will happen in the following PHP code for “CodeIgniter” and it leads to the not unique table/alias CodeIgniter error. A quick overview of the code shows that the sample code selects data from the “web_service” table and again joins it to the same table.

<?php

$this->database_connection->select(‘*’);

$this->database_connection->from(‘web_service’);

$this->database_connection->join(‘user’, ‘user.u_email = web_service.u_email’, ‘inner’);

$this->database_connection->join(‘web_service’, ‘web_service.u_email = user.u_email’, ‘inner’);

$query = $this->database_connection->get();

?>

– Two Tables Have the Same Name and Lower_case_table_names=1

The “lower_case_table_names” controls the letter case of database tables and names. This allows you to have two tables with names like “Table1” and “table1” in your database. Now, when you attempt to dump the table using MySQL dump, it’ll cause the mysqldump: got error: 1066: not unique table/alias error.Not Unique Table Alias Causes

– Your Code Has Duplicate Aliases or Models

Just like how a lack of aliases can lead to the “unique” error in SQL, the duplicates can lead to errors like the er_nonuniq_table not unique table/alias typeorm error. For example, in the following query builder code, we used “site_users” twice in the “left” join statement. Behind the scenes, the execution of this code will cause an error because SQL cannot differentiate between them.

const qb = getRepository(name_of_your_entity_class)

.createQueryBuilder(“name_of_entity”)

.skip(size * (page – 1))

.take(size)

.orderBy(‘name_of_entity.created_at’, orderBy)

.leftJoinAndSelect(“name_of_entity.approvedBy”, “site_users”)

.leftJoinAndSelect(“name_of_entity.user”, “site_users”)

.select([‘name_of_entity’, ‘site_users.email’, ‘site_users.id’, ‘site_users.first_name’, ‘site_users.last_name’])

Also, duplicate models in your code can lead to the not unique table/alias sequelize error. That’s what is going on in the following code. We used the same model, “AccountHolder” twice in the “include” property. Like the previous example, this will cause an error when your application runs the code.

models.Order.findOne({

include: [

{

model: models.Provider,

attributes: [‘id’,’userId’],

include : [{

model : models.AccountHolder,

attributes: [‘first_name’,’last_name’,’phone_number’]

},{

model : models.AccountHolder,

attributes: [‘phone_number’]

}]

}

]

})

How Your SQL Statements Can Have Unique Tables and Aliases?

Your SQL statements can have a unique table or aliases if you do any of the following:

  • Use an alias when you’re joining tables
  • Don’t join the same table
  • Rename your tables before a database dump
  • Assign unique aliases to models in TypeORM
  • Assign aliases to associations or relationships

– Use an Alias When You’re Joining Tables

Always use an alias in your SQL SELECT statement to prevent the “unique” table or aliases SQL error. With an alias, you can assign temporary names to the tables, and you can prevent conflicts during database joins. The following is another version of the first SQL SELECT, this time, we’ve updated it to prevent an error.

SELECT tech_articles . * , article_sections.title, article_categories.title, account_users.name, alias_account_users.name

FROM tech_articles

INNER JOIN article_sections ON tech_articles.section_id = article_sections.id

INNER JOIN article_categories ON tech_articles.category_id = article_categories.id

INNER JOIN account_users ON tech_articles.author_id = account_users.id

LEFT JOIN account_users alias_account_users ON tech_articles.modified_by = alias_account_users.id

WHERE tech_articles.id = ‘1’

For our second example, we used an alias the second time that we called “account_users” from the “tech_articles” table. By doing this, SQL can tell the tables apart and will not throw an error.

SELECT sp.sp_ID, p.p_Title, acc.ea_ID, acc.uName, acc.access_Level, c.fName, c.lName

FROM software_projects sp

INNER JOIN engineers_account acc

ON sp.AccountID = acc.ea_ID

INNER JOIN Project p

ON sp.sp_ID = p.p_ID

INNER JOIN Clients c

ON acc.ea_ID = c.ea_ID

WHERE acc.access_Level = ‘Client’;

– Don’t Join the Same Table

The rule is to join columns from one table to columns in another table. Now, the following is a rewrite of a previous example that joined a table to itself using an SQL SELECT statement. Now, we’ve updated the code to prevent the error in the LEFT JOIN statement.

SELECT Shares.share_price, InvestorsShares.share_id, InvestorsShares.Quantity

FROM Shares

LEFT JOIN InvestorsShares on Shares.share_id = InvestorsShares.share_id

WHERE Shares.share_id = <random_number />

Up next, the following is the correct sample of the “CodeIgniter” code that caused an error.

$this->database_connection->select(‘*’);

$this->database_connection->from(‘web_service’);

$this->database_connection->join(‘user’, ‘user.e_email = web_service.e_email’, ‘inner’);

$query = $this->database_connection->get();

– Rename Your Tables Before a Database Dump

To prevent any errors about unique tables or aliases during a database dump, check your tables and rename similar table names. So, if you have table names like “Table1” and “table1” and “lower_case_table_names=1”, rename either of the tables to prevent a conflict.Not Unique Table Alias Fixes

You can use any of the following syntaxes to rename your database tables:

  • ALTER TABLE name_of_old_table RENAME name_of_new_table;
  • RENAME TABLE name_of_old_table TO name_of_new_table;
  • RENAME TABLE name_of_old_table TO name_of_new_table, name_of_old_table TO name_of_new_table;

– Assign Unique Aliases to Models in Typeorm

If your TypeORM code shows an error about unique tables and aliases, it’s because you have duplicates. To fix this, use unique aliases in your SQL JOIN statements. The following is a rewrite of the previous code that used duplicate aliases in the SQL code. This time, the code has unique aliases that will prevent the error.

const qb = getRepository(name_of_your_entity_class)

.createQueryBuilder(“name_of_entity”)

.skip(size * (page – 1))

.take(size)

.orderBy(‘name_of_entity.created_at’, orderBy)

.leftJoinAndSelect(“name_of_entity.approvedBy”, “first_site_users”)

.leftJoinAndSelect(“name_of_entity.user”, “second_site_users”)

.select(

[

‘name_of_entity’,

‘first_site_users.email’,

‘first_site_users.id’,

‘first_site_users.first_name’,

‘first_site_users.last_name’,

‘first_site_users.email’,

‘second_site_users.id’,

‘second_site_users.first_name’,

‘second_site_users.last_name’

]);

– Assign Aliases to Associations or Relationships

The use of aliases in your associations or models when using sequelize will prevent any error about unique tables and aliases. In the following, we’ve updated the code to use an alias. Afterward, we included the aliases and not the duplicates that caused the error in the first place.

Provider.belongsTo/haveMany/any…(AccountHolder, {as: ‘AH_1’});

Provider.belongsTo/haveMany/any…(AccountHolder, {as: ‘AH_2’});

include: [{

model: models.Provider,

attributes: [‘id’, ‘userId’],

include: [{

model: models.AccountHolder,

as : ‘AH_2’ // Use the alias here

attributes: [‘first_name’, ‘last_name’, ‘phone_number’]

}, {

model: models.AccountHolder,

as : ‘AH_1’ // And here as well.

attributes: [‘phone_number’]

}]

}]

Conclusion

This article discussed why your SQL statements would lead to an error about unique tables and aliases. Then in the second half of the article, we explained how to fix them, and the following is a quick summary of it all:

  • A lack of aliases in your SQL statements will lead to an error about a unique table/alias.
  • Joining a table itself will cause an error about unique tables and aliases.
  • You can fix the “no unique table/alias” SQL error using aliases where it’s needed.
  • Update your TypeORM code to use aliases, and you’ll prevent the unique table/alias error.
  • Check your database tables for identical names before dumping the whole database.

What you’ve learned in this article will make you a good SQL developer. The rule is: to use aliases when needed and don’t duplicate them if you want to prevent an error.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Here is a starting point. V1, V2, V3 are aliases, if you even need them all.

You need to bring in tables before you reference them (not in the first select row, but in the joins after the select row).

In other words, you can reference them in the select column list. But you cannot reference them in joins if they are not brought in.

You can’t reference GEBEAUTE before you have brought it in

there are 2 ways of bringing it in

  • the from XXX clause (that is your first table available brought in)
  • the join XXX clause (that brings in tables 2 and beyond)

.

select VERANSTALTUNG.v_name, V_TYP.typ, RAUM.raumname, GEBEAUTE.gebeaute_name
From VERANSTALTUNG V1
JOIN VERANSTALTUNG V2 on V2. something
JOIN VERANSTALTUNG V3 on V3. something
JOIN RAUM on RAUM.gebeaute_id=GEBEAUTE.gebeaute_id -- error here still, see below

note you still haven’t brought in V_TYP or GEBEAUTE

it’s a mess. Less of a mess, but inching toward happiness.


Here is a simple illustration of it

line1:   select A.col1,B.col2,C.col3
line2:   from table1 A
line3:   join table2 B on B.blahblah=A.something
line4:   join table3 C on C.typ_id=D.month_id

It look good until line4. Because table D is not brought in yet.

Я использую mysql workbench и mysql server для запроса базы данных. У меня есть две таблицы t1 и t2 с одним столбцом t1_name и t2_name. t2 имеет 3 миллиона записей, а t1 — 1 миллион.

Мне нужно выбрать все t2_names где t2_names не равно t1_name или не подстрока t1_name. Когда я попробую выполнить запрос ниже:

SELECT DISTINCT 't2_name'
FROM 't2', 't1'
't2'.'t2_name' NOT LIKE CONCAT('%','t1'.'t1_name','%'));

Я получаю эту ошибку:

mysql Код ошибки: 1066. Не уникальная таблица/псевдоним: ‘t2’

Можете ли вы объяснить и исправить мой запрос, пожалуйста? Ранее я сделал это сообщение и попробовал этот запрос:

SELECT DISTINCT 't2_name'
FROM 't2'
WHERE NOT EXISTS (SELECT * FROM 't1'
                    WHERE 't2_name' LIKE CONCAT('%','t2_name','%'));

но он берет навсегда и никогда не заканчивается.

Поделиться

Источник

3 ответа

Начните с квалификации всех имен столбцов. Это все еще вызывает ошибку?

SELECT DISTINCT t2.t2_name
FROM t2 JOIN
     t1
     ON t2.t2_name NOT LIKE CONCAT('%', t1.t1_name, '%');

Если ваша проблема — это производительность, она not exists будет лучше, если не будет distinct:

SELECT t2_name
FROM t2
WHERE NOT EXISTS (SELECT 1
                  FROM t1
                  WHERE t2.t2_name LIKE CONCAT('%', t1.t1_name, '%')
                 );

Однако это не будет большим улучшением. К сожалению, like запросы с такими подстановочными знаками крайне неэффективны. Часто вы можете структурировать модель данных, чтобы вы могли написать более эффективный запрос.

Gordon Linoff

Поделиться

Вам не хватает ключевого слова WHERE. Парсер считает, что t2 должен быть псевдонимом для t1 как следует t1. Но t2 уже занято предыдущим t2.

Вставьте WHERE (и удалите последнее закрытие )):

SELECT DISTINCT 't2_name'
FROM 't2', 't1'
WHERE 't2'.'t2_name' NOT LIKE CONCAT('%','t1'.'t1_name','%');

Боковое замечание: я боюсь, что ваша попытка построить картезианский продукт не будет лучше, чем NOT EXISTS. Скорее всего, он выполняет много, намного хуже…

sticky bit

Поделиться

Я думаю, что вы опечалили второе предложение, и оно должно сказать:

SELECT DISTINCT 't2_name'
FROM 't2'
WHERE NOT EXISTS (SELECT * FROM 't1'
                    WHERE 't1_name' LIKE CONCAT('%','t2_name','%'));

На данный момент вы эффективно сравниваете t2_name с самим собой.

В любом случае, это будет весело, потому что mysql собирается выполнить сканирование таблицы. Взгляните на структуру данных и контент и посмотрите, лучше ли вам выполнять очистку или реструктуризацию данных, прежде чем пытаться использовать ее для анализа.

MandyShaw

Поделиться

Ещё вопросы

  • 1TextBox не обновляет свой визуальный элемент, когда определен формат строки
  • 0отправлять только заполненные поля. если пусто, то не отправляйте по электронной почте. php форма для отправки по электронной почте
  • 0ngRoute решает проблему с инжектором
  • 0Передача переменной из .htaccess на страницу PHP
  • 1Как мы проверяем, совместимо ли значение объекта с полем примитивного типа в Java
  • 0О выравнивании данных конкретной структуры
  • 0координаты XYZ из reprojectImageTo3D opencv
  • 0Использование массива в качестве условия в предложении where codeigniter
  • 0Странный вывод из exec ()
  • 1Plotly / dash — модуль ‘dash_html_components’ не имеет члена ‘Div’
  • 1Внедрение в конструктор: как уменьшить количество параметров?
  • 0Object [object Object] не имеет метода
  • 0Внутреннее исключение: java.sql.SQLSyntaxErrorException: пользователю не хватает привилегии или объект не найден: SEQUENCE, но я использую MySQL
  • 0Проблема с повторяющимися кнопками поля формы
  • 0Компиляция и использование OpenCV
  • 1Как выбрать между различными условиями, зависящими от другой переменной
  • 1Как изменить значение атрибута стиля программно?
  • 1Эквивалент adControl.HasAd в Windows Phone 8.0
  • 0Проблема с SQL-запросом (работа с 3 таблицами)
  • 0не может скомпилировать opencv программы в ubuntu
  • 0Hibernate: Можно ли использовать Like и In вместе в Named Query?
  • 0как установить атрибуты JsTree
  • 1Xming: почему JFrame потерял фокус, когда установлен Undecorated (true)?
  • 0Каковы некоторые популярные базы данных на основе строк и столбцов?
  • 1Как я могу найти координаты различных значений?
  • 1Vue.js + Require.js расширяющий родительский
  • 1Удаление одинаковых выбросов в двух временных сериях
  • 1WCF замедляется с несколькими запросами
  • 0Поменяйте местами два HTML-тега, между которыми есть некоторые фиксированные теги
  • 0Отправить одну форму для той же модели с множеством User_id, выбранным с окном select2 в рельсах 3
  • 1Получение позиции указания элемента из localStorage
  • 1Модификация Outlook «щелкнуть правой кнопкой мыши по контакту»
  • 0Создать стену для поста из блоков
  • 0Как создать таблицу «соединения» с информацией о двух отдельных таблицах в MySQL?
  • 1Потоковые mp3-файлы из хранилища Firebase
  • 1Bukkit Плагин Minecraft Сундуки заполнить и построить из класса с INT в списке
  • 0Как вставить вывод сложной команды терминала linux в таблицу базы данных mysql
  • 1Восстанавливаемое веб-задание Azure (не удалять из очереди)
  • 1JSF Hibernate Критерии API
  • 1Как остановить масштабирование навигационной панели инструментов Matplotlib при обновлении графика?
  • 0Я хочу отключить кнопку Время входа в систему.
  • 0Загрузить всплывающее окно jQuery при загрузке страницы, используя данные URL?
  • 0Как получить метку времени из строки даты с часовым поясом, PHP?
  • 0MySQL: как выбрать min (), используя подзапрос и объединения
  • 1Ветвление и (пере) объединение пар значений в RxJS
  • 0Фон раздела div имеет необъяснимые отступы. Почему?
  • 0Подключение стека AWS LAMP к базе данных MySQL с использованием проблем PHP
  • 0Я пытаюсь сделать регистрационную форму с MySQL в Java, и это дает мне ошибку
  • 1Шкала оценок в Java
  • 1Как заставить тестовый прогон последним в visual studio с помощью NUnit

Сообщество Overcoder

You joined clients twice in the same FROM clause, that’s throwing the error.

The two incarnations of the table need to have different aliases (chosen: cl_to and cl_from):

SELECT request.*, 
       cl_to  .ClientName AS ToClient, 
       cl_from.ClientName AS FromClient, 
       drivers.DriName, requesttype.ReqTName 
FROM request
    INNER JOIN clients AS cl_to    -- alias 1 
        ON cl_to.ClientID = request.ReqToClient
    INNER JOIN clients AS cl_from   -- alias 2
        ON cl_from.ClientID = request.ReqFromClient
    INNER JOIN drivers
        ON drivers.DriID = request.DriID
    INNER JOIN requesttype
        ON requesttype.ReqTID = request.ReqTID ;

I’d prefer to use (short) aliases for all tables:

SELECT rq.*, 
       cl_to  .ClientName AS ToClient, 
       cl_from.ClientName AS FromClient, 
       dr.DriName, rt.ReqTName 
FROM request AS rq
    INNER JOIN clients AS cl_to   ON cl_to.ClientID = rq.ReqToClient
    INNER JOIN clients AS cl_from ON cl_from.ClientID = rq.ReqFromClient
    INNER JOIN drivers AS dr      ON dr.DriID = rq.DriID
    INNER JOIN requesttype AS rt  ON rt.ReqTID = rq.ReqTID ;

Понравилась статья? Поделить с друзьями:
  • Ошибка 1072 mysql
  • Ошибка 1066 02 рено премиум
  • Ошибка 1070 сразу после запуска служба зависла
  • Ошибка 1065 ниссан теана j31
  • Ошибка 1065 ниссан альмера классик