Sql ошибка 1066

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.

I have two MySQL statemenents:

SELECT PRODUCTS.REFERENCE,PRODUCTS.NAME,PRODUCTS.PRICEBUY,PRODUCTS.PRICESELL,
       SUM(TICKETLINES.UNITS) AS UNITS,
       SUM(TICKETLINES.PRICE * TICKETLINES.UNITS) AS SUBTOTAL,
       SUM((TICKETLINES.PRICE * TICKETLINES.UNITS) * TAXES.RATE) As TAXES,
       SUM(TICKETLINES.PRICE * TICKETLINES.UNITS)
        + SUM((TICKETLINES.PRICE * TICKETLINES.UNITS) * TAXES.RATE) AS GROSSTOTAL
FROM TICKETLINES
LEFT OUTER JOIN PRODUCTS ON TICKETLINES.PRODUCT = PRODUCTS.ID
LEFT OUTER JOIN TICKETS ON TICKETS.ID = TICKETLINES.TICKET
LEFT OUTER JOIN RECEIPTS ON RECEIPTS.ID = TICKETS.ID, TAXES
WHERE RECEIPTS.ID = TICKETS.ID AND TICKETS.ID = TICKETLINES.TICKET
AND TICKETLINES.PRODUCT = PRODUCTS.ID
AND TICKETLINES.TAXID = TAXES.ID
GROUP BY PRODUCTS.REFERENCE, PRODUCTS.NAME,PRODUCTS.PRICEBUY,PRODUCTS.PRICESELL
ORDER BY GROSSTOTAL DESC
LIMIT 10

and

SELECT PRODUCTS.ID, PRODUCTS.REFERENCE, PRODUCTS.CODE, PRODUCTS.NAME, PRODUCTS.ISCOM,
       PRODUCTS.ISSCALE, PRODUCTS.PRICEBUY, PRODUCTS.PRICESELL, PRODUCTS.TAXCAT,
       PRODUCTS.CATEGORY,PRODUCTS.ATTRIBUTESET_ID, PRODUCTS.IMAGE, PRODUCTS.ATTRIBUTES,
       PRODUCTS.ISKITCHEN, PRODUCTS.ISSERVICE, PRODUCTS.DISPLAY, PRODUCTS.ISVPRICE,
       PRODUCTS.ISVERPATRIB, PRODUCTS.TEXTTIP, PRODUCTS.WARRANTY, PRODUCTS.STOCKUNITS,
       TAXES.NAME, TAXES.RATE, PRODUCTS.STOCKVOLUME
FROM PRODUCTS
INNER JOIN PRODUCTS_CAT ON PRODUCTS.ID=PRODUCTS_CAT.PRODUCT
JOIN TAXCATEGORIES ON PRODUCTS.TAXCAT=TAXCATEGORIES.ID
JOIN TAXES ON TAXCATEGORIES.ID=TAXES.ID
ORDER BY PRODUCTS.NAME

Now, I am trying to combine these two statements into one, here is what I’ve got:

SELECT PRODUCTS.ID, PRODUCTS.REFERENCE, PRODUCTS.CODE, PRODUCTS.NAME, PRODUCTS.ISCOM,
       PRODUCTS.ISSCALE, PRODUCTS.PRICEBUY, PRODUCTS.PRICESELL, PRODUCTS.TAXCAT,
       PRODUCTS.CATEGORY, PRODUCTS.ATTRIBUTESET_ID, PRODUCTS.IMAGE, PRODUCTS.ATTRIBUTES,
       PRODUCTS.ISKITCHEN, PRODUCTS.ISSERVICE, PRODUCTS.DISPLAY, PRODUCTS.ISVPRICE,
       PRODUCTS.ISVERPATRIB, PRODUCTS.TEXTTIP, PRODUCTS.WARRANTY, PRODUCTS.STOCKUNITS,
       TAXES.NAME, TAXES.RATE, PRODUCTS.STOCKVOLUME,
       SUM(TICKETLINES.UNITS) AS UNITS,
       SUM(TICKETLINES.PRICE*TICKETLINES.UNITS) AS SUBTOTAL,
       SUM((TICKETLINES.PRICE*TICKETLINES.UNITS)*TAXES.RATE) AS TAXESTOTAL,
       SUM(TICKETLINES.PRICE*TICKETLINES.UNITS)
         +SUM((TICKETLINES.PRICE*TICKETLINES.UNITS)*TAXES.RATE) AS GROSSTOTAL
FROM TICKETLINES
INNER JOIN PRODUCTS_CAT ON PRODUCTS.ID=PRODUCTS_CAT.PRODUCT
JOIN TAXCATEGORIES ON PPRODUCTS.TAXCAT=TAXCATEGORIES.ID
JOIN TAXES ON TAXCATEGORIES.ID=TAXES.ID
LEFT OUTER JOIN PRODUCTS ON TICKETLINES.PRODUCT=PRODUCTS.ID
LEFT OUTER JOIN TICKETS ON TICKETS.ID=TICKETLINES.TICKET
LEFT OUTER JOIN RECEIPTS ON RECEIPTS.ID=TICKETS.ID, TAXES
WHERE RECEIPTS.ID=TICKETS.ID AND TICKETS.ID=TICKETLINES.TICKET
AND TICKETLINES.PRODUCT=PRODUCTS.ID
AND TICKETLINES.TAXID=TAXES.ID
ORDER BY PRODUCTS.NAME

Why upper statement does not execute and reports error Error Code: 1066. Not unique table/alias: 'TAXES'
?

Solution 1

You need to give the user table an alias the second time you join to it

e.g.

SELECT article . * , section.title, category.title, user.name, u2.name 
FROM article 
INNER JOIN section ON article.section_id = section.id 
INNER JOIN category ON article.category_id = category.id 
INNER JOIN user ON article.author_id = user.id 
LEFT JOIN user u2 ON article.modified_by = u2.id 
WHERE article.id = '1'

Solution 2

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

Solution 3

You have mentioned «user» twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:

FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified_by = **user2**.id
WHERE article.id = '1'

(You may need something different — I guessed which user is which, but the SQL engine won’t guess.)

Also, maybe you only needed one «user». Who knows?

Related videos on Youtube

mysqldump: Got error: 1066: Not unique table/alias: 'foo' when using LOCK TABLES when...

01 : 42

mysqldump: Got error: 1066: Not unique table/alias: ‘foo’ when using LOCK TABLES when…

MySQL : Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

01 : 12

MySQL : Why does this SQL code give error 1066 (Not unique table/alias: ‘user’)?

Databases: mysqldump: Got error: 1066: Not unique table/alias: 'temp1' when using LOCK TABLES

01 : 26

Databases: mysqldump: Got error: 1066: Not unique table/alias: ‘temp1’ when using LOCK TABLES

SQLSTATE[42000] Syntax error or access violation 1066 Not unique table/alias on relationship - MySQ

02 : 25

SQLSTATE[42000] Syntax error or access violation 1066 Not unique table/alias on relationship — MySQ

Not unique table/alias - MySQL

01 : 05

Not unique table/alias — MySQL

MySQL & PHP - Not unique table/alias - MySQL

01 : 15

MySQL & PHP — Not unique table/alias — MySQL

Why does this SQL code give error 1066 (Not unique table/alias user) - MySQL

01 : 03

Why does this SQL code give error 1066 (Not unique table/alias user) — MySQL

Why does this SQL code give error 1066 (Not unique table/alias user) - SQL

01 : 03

Why does this SQL code give error 1066 (Not unique table/alias user) — SQL

Why does this SQL code give error 1066 (Not unique table/alias user) - MySQL

01 : 03

Why does this SQL code give error 1066 (Not unique table/alias user) — MySQL

Comments

  • This is my table structure:

    alt text

    The error message is:

    #1066 — Not unique table/alias: ‘user’

    The following is my code.

    SELECT article.* , section.title, category.title, user.name, user.name
    FROM article
    INNER JOIN section ON article.section_id = section.id
    INNER JOIN category ON article.category_id = category.id
    INNER JOIN user ON article.author_id = user.id
    LEFT JOIN user ON article.modified_by = user.id
    WHERE article.id = '1'
    

  • And, perhaps better: ... LEFT JOIN user AS author ON article.author_id = author.id LEFT JOIN user AS modifier ON article.modified_by = modifier.id. Aliasing both references to user, in other words, and giving them meaningful names (though I also use u1 and u2 in such situations).

  • Man this is the real deal in INNER JOIN !!

Recents

Я использую 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','%'));

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

29 июль 2018, в 15:44

Поделиться

Источник

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
29 июль 2018, в 11:01

Поделиться

Вам не хватает ключевого слова 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
29 июль 2018, в 10:58

Поделиться

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

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

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

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

MandyShaw
29 июль 2018, в 10:45

Поделиться

Ещё вопросы

  • 0Как исчезнуть элемент при переходе?
  • 1Приложение магазина C #, получающее переменные данные Json
  • 1Android: эффективно скопируйте zip-файл с тысячами файлов из ресурсов во внутреннее хранилище
  • 1Как добавить аннотации Java в JNI SWIG API?
  • 1Использование свойства text = {binding var} для проверки значения введите в элемент управления textbox
  • 0Разбор поплавка для карт Google с использованием Javascript / jQuery
  • 1сортировка по дате в базе данных Firebase
  • 1Отображение только уникальных элементов в массиве
  • 0Как использовать React JSX внутри угловой директивы
  • 0Еще один пример соединения с запросом mysql
  • 0Класс 2D массив превращается в arr [] при вызове функцией C ++
  • 1Я хочу скачать JDK Windows 32 бит
  • 1Иметь представление обтекания содержимого, но соответствовать родительскому, если есть свободное место
  • 0Как обновить графику, чтобы избежать черного экрана?
  • 0не добавлять дубликаты в корзину
  • 0Как может angularjs контроллер доступа к функциям в non-angularjs iframe?
  • 0Реально ли реализовать PHP-демон, который будет поддерживать постоянную связь с websocket-сервером?
  • 0преобразование из двоичной строки в int с использованием strtoll?
  • 1Передача текста и значения в ComboBox
  • 1Python: OpenCV findHomography входы
  • 0Различные результаты PHP между терминалом и браузером
  • 0Сова Карусель не работает в angularjs частичный вид
  • 0QSystemTrayIcon не отображается
  • 1Как сделать имена столбцов чувствительными к регистру Sqlite3 в Python?
  • 1Невозможно установить пакет Python с pip, требуется Microsoft Visual C ++ 14.0
  • 1Изменить цвет сюжета FEVD
  • 1WPF ItemSource DataGrid TreeViewItem ошибка дополнительной строки
  • 1Есть ли разница между клиентом MDI, контейнером MDI и родителем MDI?
  • 01066 — Не уникальный стол / псевдоним: «художники»
  • 0CSS — плавающая проблема для адаптивного дизайна
  • 0Ошибка при загрузке изображения: вызов функции-члена guessExtension
  • 1Решить с помощью решателя Z3 условие с длиной массива произвольного размера
  • 1Сравнивайте телефонные номера без учета какого-либо формата в Linq с объектами, а также проверяйте производительность
  • 1Передача более одного значения из списка DropDown
  • 1Заполните словарь несколькими понятиями
  • 0Как сохранить выбор флажка с тем же именем и идентификатором
  • 1Как получить, если приложение запрашивает разрешение?
  • 0C # UWP Форма входа, проверяющая учетные данные в удаленной базе данных MySQL
  • 0angular $ resource получает дополнительную информацию
  • 1Система маршрутизации MVC
  • 0МОЯ SMTP-почта продолжает поступать как нежелательная
  • 1Как я могу вставить магазин в панель инструментов панели?
  • 0Ошибка типа Javascript: oauth не является конструктором
  • 0Не удается сбросить форму с помощью ‘$ setPristine’
  • 0Распечатать / показать пароль пользователя в mysql CLI
  • 0Пользовательские домены для одного сайта
  • 1Невозможно добавить изображение к кнопке с помощью getResource () (получить NullPointerException — создание проекта с помощью муравья)
  • 0Переход на другую страницу (через HTML5, CSS3 и JS) в iPad по Swipe (с анимацией слайдов)
  • 1Проблемы запуска Spring с JUnit
  • 2Изменить размер текста на positveButtonText в диалоговом окне EditTextPreference

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:
  • Sql access ошибка синтаксиса пропущен оператор
  • Sql 303 ошибка
  • Spyder python ошибка
  • Spv69t70ru ошибка e09
  • Spu orb произошли некритические ошибки