I have 2 tables. tbl_names
and tbl_section
which has both the id
field in them. How do I go about selecting the id
field, because I always get this error:
1052: Column 'id' in field list is ambiguous
Here’s my query:
SELECT id, name, section
FROM tbl_names, tbl_section
WHERE tbl_names.id = tbl_section.id
I could just select all the fields and avoid the error. But that would be a waste in performance. What should I do?
Shadow
33.4k10 gold badges50 silver badges62 bronze badges
asked Jul 10, 2011 at 1:08
Wern AnchetaWern Ancheta
22.2k38 gold badges99 silver badges138 bronze badges
SQL supports qualifying a column by prefixing the reference with either the full table name:
SELECT tbl_names.id, tbl_section.id, name, section
FROM tbl_names
JOIN tbl_section ON tbl_section.id = tbl_names.id
…or a table alias:
SELECT n.id, s.id, n.name, s.section
FROM tbl_names n
JOIN tbl_section s ON s.id = n.id
The table alias is the recommended approach — why type more than you have to?
Why Do These Queries Look Different?
Secondly, my answers use ANSI-92 JOIN syntax (yours is ANSI-89). While they perform the same, ANSI-89 syntax does not support OUTER joins (RIGHT, LEFT, FULL). ANSI-89 syntax should be considered deprecated, there are many on SO who will not vote for ANSI-89 syntax to reinforce that. For more information, see this question.
answered Jul 10, 2011 at 1:31
OMG PoniesOMG Ponies
324k80 gold badges520 silver badges499 bronze badges
1
In your SELECT
statement you need to preface your id with the table you want to choose it from.
SELECT tbl_names.id, name, section
FROM tbl_names
INNER JOIN tbl_section
ON tbl_names.id = tbl_section.id
OR
SELECT tbl_section.id, name, section
FROM tbl_names
INNER JOIN tbl_section
ON tbl_names.id = tbl_section.id
answered Jul 10, 2011 at 1:11
2
You would do that by providing a fully qualified name, e.g.:
SELECT tbl_names.id as id, name, section FROM tbl_names, tbl_section WHERE tbl_names.id = tbl_section.id
Which would give you the id of tbl_names
answered Jul 10, 2011 at 1:12
halfdanhalfdan
33.4k8 gold badges78 silver badges87 bronze badges
2
Already there are lots of answers to your question, You can do it like this also. You can give your table an alias name and use that in the select query like this:
SELECT a.id, b.id, name, section
FROM tbl_names as a
LEFT JOIN tbl_section as b ON a.id = b.id;
answered May 25, 2016 at 6:28
M.JM.J
2,6844 gold badges23 silver badges34 bronze badges
The simplest solution is a join with USING
instead of ON
. That way, the database «knows» that both id
columns are actually the same, and won’t nitpick on that:
SELECT id, name, section
FROM tbl_names
JOIN tbl_section USING (id)
If id
is the only common column name in tbl_names
and tbl_section
, you can even use a NATURAL JOIN
:
SELECT id, name, section
FROM tbl_names
NATURAL JOIN tbl_section
See also: https://dev.mysql.com/doc/refman/5.7/en/join.html
answered Jun 15, 2018 at 20:21
vogvog
23.2k11 gold badges58 silver badges74 bronze badges
What you are probably really wanting to do here is use the union operator like this:
(select ID from Logo where AccountID = 1 and Rendered = 'True')
union
(select ID from Design where AccountID = 1 and Rendered = 'True')
order by ID limit 0, 51
Here’s the docs for it https://dev.mysql.com/doc/refman/5.0/en/union.html
answered May 28, 2015 at 20:34
Bryan LegendBryan Legend
6,7601 gold badge59 silver badges60 bronze badges
0
If the format of the id’s in the two table varies then you want to join them, as such you can select to use an id from one-main table, say if you have table_customes
and table_orders
, and tha id for orders is like «101«,»102«…»110«, just use one for customers
select customers.id, name, amount, date from customers.orders;
answered Mar 23, 2014 at 6:16
SELECT tbl_names.id, tbl_names.name, tbl_names.section
FROM tbl_names, tbl_section
WHERE tbl_names.id = tbl_section.id
answered May 22, 2017 at 13:47
nikunjnikunj
231 silver badge9 bronze badges
When working with programs that pull data from databases, you may occasionally run across different types of errors. Many of them are fixable, specifically if you are coding your own SQL queries. This article describes the ‘1052 Column in where clause is ambiguous‘ error and how to correct it.
The Error
This type of error occurs when a SQL query is working with more than one table. Our example below is using two tables within an ecommerce program and generates the following error:
Notice: Error: Column ‘firstname’ in where clause is ambiguous
Error No: 1052
SELECT COUNT(*) AS total FROM oc_customer c LEFT JOIN oc_address a ON (c.customer_id = a.customer_id) WHERE CONCAT(firstname, ‘ ‘, lastname) LIKE ‘%john%’
What causes the error
The query gives each table an alias, the oc_customer table gets an alias of c and the oc_address table gets an alias of a. This is used to define which table the column is supposed to come from, such as the section of the query c.customer_id = a.customer_id. This is the same as saying oc_customer.customer_id = oc_address.customer_id. There is another section that has column names but the script fails to identify which table to look into, CONCAT(firstname, ‘ ‘, lastname). Since both the oc_customer and oc_address tables have columns named firstname and lastname, the server does not know which table to work with, and thus throws the error.
Fixing the error
To fix this, simply add the tablename or alias for the table you want to work with. If you are writing the query yourself, this is a bit easier to deal with as you will know which table you meant to use. In our example, we should add the alias for the oc_customer table, c, to the column names. Our code snippet would look like this: CONCAT(c.firstname, ‘ ‘, c.lastname) making the whole query appear as below.
SELECT COUNT(*) AS total FROM oc_customer c LEFT JOIN oc_address a ON (c.customer_id = a.customer_id) WHERE CONCAT(c.firstname, ‘ ‘, c.lastname) LIKE ‘%john%’
If you are working with a developer or a professional level program (open source or purchased) you will need to let them know of the error. They will be able to fix the issue in their next release.
The query will now run correctly as it knows which table to work with on all columns.
В этом посту вы узнаете, что значит ошибка «ORA-00918: column ambiguously defined» и как её решить. Ошибка возникает, когда при объединении в двух таблицах присутствуют колонки с одинаковым названием и непонятно, к какой таблице относится колонка.
Для воспроизведения ошибки, создаём две простых таблицы с одинаковыми колонками — цифровой и текстовой. И number_column, и text_column присутствуют в обоих таблицах.
CREATE TABLE test_table1(number_column NUMBER, text_column VARCHAR2(50) )
CREATE TABLE test_table2(number_column NUMBER, text_column VARCHAR2(50) )
Выпоняем запрос SQL с объединением через JOIN, выбираем значения number_column, text_column из таблиц test_table1 и test_table2, в которых number_column из одной равняется number_column из другой, и number_column равняется единице.
SELECT number_column, text_column FROM test_table1 JOIN test_table2 ON number_column = number_column WHERE number_column = 1
Уже прочитав предложение сразу становится понятным, что невозможно определить к какой из двух таблиц относится number_column, а также text_column, что менее очевидно. После выполнения запроса Apex SQL Workshop (или любой другой инструмент для работы с базами данных Oracle) выдаёт такую ошибку:
Скриншот 1: Ошибка ORA-00918: column ambiguously defined
Исправить ситуацию можно двумя методами. В первом просто прописывает название таблицы перед названием колонки.
SELECT test_table1.number_column, test_table1.text_column FROM test_table1 JOIN test_table2 ON test_table1.number_column = test_table2.number_column WHERE test_table1.number_column = 1
Второй метод удобнее. В нём используются алиасы названий таблиц, в нашем примере t1 для test_table1 и t2 для test_table2.
SELECT t1.number_column, t1.text_column FROM test_table1 t1 JOIN test_table2 t2 ON t1.number_column = t2.number_column WHERE t1.number_column = 1
Кстати, в MySQL эта ошибка называется «#1052 — Column ‘number_column’ in field list is ambiguous» и лечится тем же способом. phpMyAdmin выдаёт при такой ошибке следующее сообщение:
Скриншот 2: Ошибка MySQL #1052 — Column in field list is ambiguous
Понравился пост? Поделись в соцсетях и подписывайся на аккаунты в Twitter и Facebook!
Thats says it all meaning the column is present in both the tables and you need to explicitly mention which table column you are referring to something as
CREATE VIEW rending AS SELECT *
FROM ranged_weapons, melee_weapons
WHERE ranged_weapons.Dam_Type = 'Rending';
UPDATE : From the given table structures using the above code will show duplicate column name error since lot of column name is same across the tables.
The best thing is to select the columns explicitly for the view using JOIN or if needed to select the same column from the other table then using different alias names. Here is an example of how we can select and create the view using JOIN
CREATE VIEW rending AS
SELECT rw.Name_,rw.Class,rw.Type_,rw.Range_,
rw.RoF,rw.Dam,rw.Dam_Type,rw.Pen ,rw.Clip,rw.Rld
FROM ranged_weapons rw
JOIN melee_weapons mw on mw.Name_ = rw.Name_
WHERE rw.Dam_Type = 'Rending';
If you want to select same columns for the view from different tables this how you can use alias
CREATE VIEW rending AS
SELECT rw.Name_,rw.Class,rw.Type_,rw.Range_,
rw.RoF,rw.Dam,rw.Dam_Type,rw.Pen ,rw.Clip,rw.Rld,
mw.Name_ as mw_Name
FROM ranged_weapons rw
JOIN melee_weapons mw on mw.Name_ = rw.Name_
WHERE rw.Dam_Type = 'Rending';
Here mw.Name_ as mw_Name
will refer to the column from melee_weapons and you can specify other column names this way if its needed for the view.
Error ‘1052’ Field is ambiguous. I understand the error that is happening, and I’ve looked at several places for the fix and then applied the inner join function in attempt to fix it. It’s still not working, and it gives me the same error.
EventNo is a primary key in the eventrequest table and a foreign key in the Eventplan table. I’m trying to list the event number, event date, and count of the event plans while only including event requests in the result if the event request has more than one related event plan with a work date in December 2013. This is my code.
SELECT EventNo, DateAuth, COUNT(PlanNo)
FROM eventplan INNER JOIN eventrequest ON eventplan.eventNo = Eventrequest.EventNo
WHERE COUNT(PlanNo) > 1 BETWEEN '2013-12-01' AND '2013-12-31';
asked Feb 21, 2016 at 20:23
4
Qualify each column in the SELECT
/WHERE
and join clauses.
So, for example I’ve qualified the EventNo
column so that it’s read from the eventplan
table in the SELECT
clause — it’s ambiguous because it is in both the eventplan
and eventrequest
tables.
SELECT eventplan.EventNo, DateAuth, COUNT(PlanNo)
FROM eventplan INNER JOIN eventrequest ON eventplan.eventNo = Eventrequest.EventNo
WHERE COUNT(PlanNo) > 1 BETWEEN '2013-12-01' AND '2013-12-31';
You may nave to do the same for DateAuth
and PlanNo
if they exist in both tables (in this specific query).
It’s good practice to always fully qualify column names — can make the query easier to read. You can always use a table alias too to cut down on typing.
answered Feb 21, 2016 at 21:38
PhilᵀᴹPhilᵀᴹ
31.5k9 gold badges80 silver badges107 bronze badges
3