- Что значит ошибка Column is ambiguous при работе с базой данных?
- Важное знание
- То же самое другими словами
- UNION ALL
- How to Solve the “Ambiguous Name Column” Error in SQL
- Give the tables an alias
- How to Solve the “Ambiguous Name Column” Error in SQL
- Conclusion
- Ambiguous column name error, how do I fix it?
- 9 Answers 9
- Not the answer you’re looking for? Browse other questions tagged sql sql-server tsql or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- «Ambiguous column name» when joining tables
- 4 Answers 4
- ORA-00918 (или #1052 в MySQL): частые ошибки новичков
Что значит ошибка Column is ambiguous при работе с базой данных?
Здравствуйте, уважаемые подписчики и гости канала!
Очень коротко — ошибка про ambiguous означает, что база данных не знает из какой из таблиц брать поле. У вас в запросе есть JOIN с одной или более таблиц и вы выбираете * (звездочку) или поле без указания имени таблиц или ее alias (если он указан).
Например, есть таблицы foo (с полями id, name, bar_id) и bar (с полями id, name). Если сделать такой запрос:
SELECT id, name from foo LEFT JOIN bar ON bar.id = foo.bar_id
То вы получите ошибку про ambiguous, так как и id и name есть в обеих таблицах. То же самое применимо к секциям про GROUP BY, ORDER BY, HAVING и т.д.
Важное знание
Очень важно знать — когда делаешь join всегда пиши alias таблиц перед всеми полями. Если этого не сделать, то запрос даже если сразу не будет падать по ambiguous, может работать до тех пор, пока в одну из таблиц не добавят поле с таким же именем. Часто это всякие user_id, creation_time и пр. А если у вас не 100% покрытие тестами (зуб даю), и тестировщик не заметит, то в продакшене будет а-та-та!
То же самое другими словами
У вас в актовом зале школы два или три класса и завучу надо позвать Васю (6А), Петю (7А) и Колю (10Б). Вот только Коли и Васи есть больше, чем в одном классе, но в одном классе есть только один человек с таким именем (это для упрощения, ведь в одной таблице не может быть двух полей с одинаковыми именами).
Значит завучу просто надо сказать Коля из 10Б и Вася из 6А и Петя из 7А подойдите, пожалуйста.
Петю, конечно, можно позвать и так, если завуч уверен, что Петя в школе всего один) Но может еще какой-то Петя туда пришел, а никто и не знает.
UNION ALL
Важно отметить, что на практике часто встречаю, что народ делает JOIN и получает ambiguous в случае, когда join и нужен-то не был, а надо было просто из двух разных таблиц получить одни и те же поля. Делают примерно такое:
SELECT Date, CampaignId, CampaignName
FROM tbl1
LEFT JOIN tbl2 ON tbl1.Date = tbl2.Date
А на самом деле хотят такое:
SELECT Date, CampaignId, CampaignName
FROM tbl1
SELECT Date, CampaignId, CampaignName
FROM tbl2
Статей про базы данных на канале много, так что, подписывайтесь, чтобы не пропустить =) Есть и про Postgres и про BigQuery, но если в целом — то ansi sql standard штука базовая и много статей часто одинаково применимы к любым базам данных, включая sql.
А на этом всё, спасибо за внимание!
Подписывайтесь на канал , ставьте лайки, оставляйте комментарии — это помогает продвижению в Дзене.
Источник
How to Solve the “Ambiguous Name Column” Error in SQL
Give the tables an alias
Oct 5, 2020 · 2 min read
At times you may want to join two tables in SQL and there are in the tables, columns with the same name.
In this case, if you join the two tables and run the query without differentiating the names of the columns that are the same, the error “Ambiguous name column” will glare at you.
How do you solve this?
There are various ways to solve the “ambiguous name column” bug. One of the simplest ways to solve it is explained below.
How to Solve the “Ambiguous Name Column” Error in SQL
For instance, you want to join two tables named TABLE1 and TABLE2. TABLE1 contains these columns — EmployeeID, Name, Salary. TABLE2 has these columns — EmployeeID, Name, Age.
First, let’s create the tables.
Note that the two tables have a “Name” column in common apart from the EmployeeID — which is always a number.
Now let’s join the tables. Run the query below:
If you run the above query, you will get this error — “Ambiguous name column”.
This means two columns have the same column name — that is the “Name” column. The SQL Machine is confused as to which “Name” out of the two tables you are referring to. It is ambiguous — not clear.
To clarify this, add the alias of either or both TABLE1 or TABLE2 to the columns having the same name. You will notice above, the alias of TABLE1 is A while that of TABLE2 is B.
So, let’s fix the bug.
Run the query. No error!
You may want to take it further by differentiating which “Name” falls in TABLE2 by writing your query like so:
Conclusion
You may give columns with the same name different names. This may make the identification of a column content difficult. A column name should describe what’s in the column.
One of the simplest ways to solve an “ambiguous name column” error — without changing column name — is to give the tables you want to join an alias. This sends a clear information to the SQL Machine the columns are different.
Источник
Ambiguous column name error, how do I fix it?
What I want to do is select a specific UserName ie USERA and update the Flags column. but I also want to update the Flags column in the Groups table to the same value.
but I keep getting : Ambiguous column name ‘Flags’.
if I do Set Groups.Flags = @Var i get : Msg 4104, Level 16, State 1, Line 1 The multi-part identifier «Groupy.Flags» could not be bound.
9 Answers 9
You need to add the alias for the Groups table. Change this:
The problem is that you haven’t specified the table name for the field «Flags» and it probably exists in more than one table in the query. Add the table name in the format «Tablename.flags» to the front of all references to fix the problem.
- In the from clause — the update target needs to be the first table there.
- In the update clause — use the table alias created in the from clause.
- In the set clause — use the table alias created in the from clause.
I once knew the reasons that this dance needs to be done this way — now I just do it out of habit. I suspect it has something to do with TSQL’s double FROM clause in DELETE statements, and the possibility of talking about Two different instances of the Groups table between the FROM and UPDATE clause. or even Two different instances of the Groups table in the from clause (think self-join).
Try SET Groups.Flags = @var in your second update
Just do alias.Flags or TableName.Flags in the update statement.
So it becomes this:
In your example: g.Flags
Here’s a workaround (albeit maybe not the best solution):
Mention the correct Table column for the ON clause to Condition
FROM database2.student student LEFT JOIN database2.college college ON student.college_id = college.college_id ORDER BY college.college_id
This Error occurs due to the Name Confusion between the Table Mention the Table column properly with the table Name This would work..
Not the answer you’re looking for? Browse other questions tagged sql sql-server tsql or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.14.41003
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
«Ambiguous column name» when joining tables
I’m having difficulty in pulling the userID from joining these two tables.
My goal is to find all vacation balance over 200 and all active userID but I keep getting an ambiguous column name for userID.
My query does work if i try to pull anything else, but I want to pull UserID instead. Any help on my query will be appreciated.
Here is my table and its columns:
Table USER
Table Balance
Here is my Query:
Here is the error I’m getting:
Msg 209, Level 16, State 1, Line 1 Ambiguous column name ‘userid’.
4 Answers 4
Because each table contains a UserID column, you need to specify from which you want the UserID to come by including the table alias in the SELECT statement:
The reason behind you getting this error is when you join two or more tables then it will comes up with a common recordset to the select while there are more than one column having the same name so the system is unable to understand which value you want to put there, that’s why system generates ambiguity in column name error message.
To avoid this error, make sure that you prefix the column name with the table name or table alias for those columns that exist in more than 1 table. Here’s an updated SELECT statement that will not generate the error:
It is a good practice to always prefix column names with the table name or table alias so that in case additional columns are added to a table that have the same name as existing columns in another table, you won’t encounter this error.
Источник
ORA-00918 (или #1052 в MySQL): частые ошибки новичков
В этом посту вы узнаете, что значит ошибка «ORA-00918: column ambiguously defined» и как её решить. Ошибка возникает, когда при объединении в двух таблицах присутствуют колонки с одинаковым названием и непонятно, к какой таблице относится колонка.
Для воспроизведения ошибки, создаём две простых таблицы с одинаковыми колонками — цифровой и текстовой. И number_column, и text_column присутствуют в обоих таблицах.
Выпоняем запрос SQL с объединением через JOIN, выбираем значения number_column, text_column из таблиц test_table1 и test_table2, в которых number_column из одной равняется number_column из другой, и number_column равняется единице.
Уже прочитав предложение сразу становится понятным, что невозможно определить к какой из двух таблиц относится number_column, а также text_column, что менее очевидно. После выполнения запроса Apex SQL Workshop (или любой другой инструмент для работы с базами данных Oracle) выдаёт такую ошибку:
Скриншот 1: Ошибка ORA-00918: column ambiguously defined
Исправить ситуацию можно двумя методами. В первом просто прописывает название таблицы перед названием колонки.
Второй метод удобнее. В нём используются алиасы названий таблиц, в нашем примере t1 для test_table1 и t2 для test_table2.
Кстати, в MySQL эта ошибка называется «#1052 — Column ‘number_column’ in field list is ambiguous» и лечится тем же способом. phpMyAdmin выдаёт при такой ошибке следующее сообщение:
Скриншот 2: Ошибка MySQL #1052 — Column in field list is ambiguous
Источник