Home >Database >Mysql Tutorial >How to Solve SQL Error 1066: Non-Unique Table Aliases in JOINs?

How to Solve SQL Error 1066: Non-Unique Table Aliases in JOINs?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-02 21:07:39614browse

How to Solve SQL Error 1066: Non-Unique Table Aliases in JOINs?

SQL Error 1066: Troubleshooting Non-Unique Table Aliases in JOIN Queries

When encountering SQL error 1066, "Not unique table/alias," it indicates that multiple occurrences of the same table are used without unique aliases to differentiate them in a JOIN query.

Consider the following example 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'

In this code, you'll notice that the "user" table is joined twice, causing the error. To resolve this issue, you need to give a unique alias to the second occurrence of the table.

The following code demonstrates the corrected query:

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'

By providing the unique alias "u2" to the second occurrence of the "user" table, the error is resolved, and you can successfully execute the query.

The above is the detailed content of How to Solve SQL Error 1066: Non-Unique Table Aliases in JOINs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn