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,7044 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 badges59 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
Есть две таблицы связанные по двум колонкам
в одной таблице (monitoring_companies)
есть колонки
- mc_id (id элемента)
- c_id (id страны покупателя)
- generator_c_id (id страны производителя)
обе эти колонки имеют идентификаторы стран , названия которых c_name хранятся в другой таблице countries
таблица countries
имеет две колонки
- c_id (id страны)
- c_name (название страны)
Мне нужно получить массив с названиями стран покупателей и производителей
Использую конструктор запросов фреймверка codeigniter
Запрос выглядит следущим образом
$this->db->select('mc_id')
->group_start()
->select('c_name AS name')->from('countries')->where('countries.c_id = monitoring_companies.c_id')
->group_end()
->or_group_start()
->select('c_name')->from('countries')->where('countries.c_id = monitoring_companies.generator_c_id')
->group_end()
->from('monitoring_companies');
$getresult = $this->db->get()->result_array();
выдает ошибку.
Not unique table/alias: ‘countries’
Выходит, мне нужно задать псевдоним таблице ‘countries’
Задаю псевдоним:
$this->db->select('mc_id')
->group_start()
->select('c_name AS name')->from('countries')->where('countries.c_id = monitoring_companies.c_id')
->group_end()
->or_group_start()
->select('c_name')->from('countries AS cscsdc')->where('cscsdc.c_id = monitoring_companies.generator_c_id')
->group_end()
->from('monitoring_companies');
тогда выдает ошибку
Column ‘c_name’ in field list is ambiguous
Если напишу просто вот так:
$this->db->select('monitoring_companies.mc_id')
->group_start()
->select('c_name AS name')->from('countries')->where('countries.c_id = monitoring_companies.c_id')
->group_end()
->from('monitoring_companies');
то получаю массив, но как видно в массиве хранится всего одна страна связанная по id покупателя
Array
(
[0] => Array
(
[mc_id] => 1
[name] => Коморские острова
)
[1] => Array
(
[mc_id] => 2
[name] => Бангладеш
)
[2] => Array
(
[mc_id] => 3
[name] => Коста Рико
)
[3] => Array
(
[mc_id] => 4
[name] => Конго
)
[4] => Array
(
[mc_id] => 7
[name] => Коморские острова
)
[5] => Array
(
[mc_id] => 23
[name] => Россия
)
)
еще попробовал такой вариант
$this->db->select('monitoring_companies.mc_id')
->group_start()
->select('buy.c_name AS name')->from('countries AS buy')->where('buy.c_id = monitoring_companies.c_id')
->group_end()
->or_group_start()
->select('gen.c_name')->from('countries AS gen')->where('gen.c_id = monitoring_companies.generator_c_id')
->group_end()
->from('monitoring_companies');
получил огромный массив с более чем 1000 элементами.
хотя в таблице monitoring_companies их 6…
перепробовал десятки вариантов, но как получить массив в котором будут храниться обе страны так и не понял…(((
В этом посту вы узнаете, что значит ошибка «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!
allonemoon 5 / 5 / 1 Регистрация: 31.10.2015 Сообщений: 260 |
||||
1 |
||||
21.08.2017, 14:37. Показов 34550. Ответов 2 Метки запрос (Все метки)
Вроде все верно ведь пишу?
#1052 — Column ‘id’ in field list is ambiguous
0 |
Модератор 4206 / 3046 / 581 Регистрация: 21.01.2011 Сообщений: 13,190 |
|
21.08.2017, 14:43 |
2 |
#1052 — Column ‘id’ in field list is ambiguous Сообщение говорит о том, что колонка id есть более чем в одной упомянутой таблице.
0 |
Павел86 11 / 11 / 2 Регистрация: 30.08.2017 Сообщений: 40 |
||||
30.08.2017, 23:53 |
3 |
|||
По идее, к названию колонки нужно добавить название таблицы. Например:
0 |
While working with tables in SQL and trying to fetch some data, you might have come across the Column ‘user_id‘ in field list is ambiguous” error. In this post, we will take a closer look at the reason behind the error followed by its solution.
What is Column ‘user_id’ in field list is ambiguous” error?
This error occurs when you are trying to fetch some data from multiple tables with the help of a join query. But if the same field name is present in both tables, and you are not passing the table name as part of the column identifier, the query will be unsuccessful.
Look at the example given below:
SQL Query
SELECT user_id, name, age, user_address, user_sex FROM user_details as ud, users as u WHERE user_id = user_id LIMIT 0, 25
Error
#1052 - Column 'user_id' in field list is ambiguous
In the above example, we are trying to fetch data from two tables, users and user_details by using table join.
users |
user_details |
|
user_id |
user_details_id |
|
name |
user_id |
|
age |
user_address |
|
user_sex |
And you can see, the name of one field user_id is present in both the tables.
In the SELECT query, you are not specifying table name to select data. So, MySQL gets confused and generates the Column ‘user_id‘ in field list is an ambiguous error.
Solution
SELECT u.user_id, u.name, u.age, ud.user_address, ud.user_sex FROM user_details as ud, users as u WHERE u.user_id = ud.user_id
In this solution, you can see that the table name is specified using dot (.). Aliases u is for users table and ud is for user_details table. So, MySQL does not get confused after encountering u.user_id and ud.user_id. The query is executed successfully.