Column reference is ambiguous ошибка

ERROR: column reference «b_id» is ambiguous

знаю что данная ошибка означает что нужно изменить где-то b_id, но что-то не могу понять где.

Вот запрос:

SELECT "b_id","b_genre","b_author","b_book_name","b_page_count","at_text","bc_name" FROM "book" LEFT JOIN "annotation" ON "b_id"="at_bid" LEFT JOIN "book_cover" ON "bc_book_id"="b_id" LEFT JOIN (SELECT "b_id" FROM "book" ORDER BY "b_id" DESC OFFSET 10 LIMIT 10 ) as t ON t.b_id = "book".b_id

Ошибка которая вываливается:

ERROR: column reference "b_id" is ambiguous LINE 1: SELECT "b_id","b_genre","b_author","b_book_name","b_page_cou... ^

Вот это, я использую как offset, limit так как если использовать прямой offset и limit запрос зависает конкретно, записей много.

LEFT JOIN (SELECT "b_id" FROM "book" ORDER BY "b_id" DESC OFFSET 10 LIMIT 10 )

База данных PostgreSQL 9.3.11

I am using PostgreSQL as my database. And I need to create an entry in the database, and if it’s already exists, just update its fields, but one of the fields should be updated only if it’s not set.

I’ve used info from this question: https://stackoverflow.com/questions/13305878/dont-update-column-if-update-value-is-null, it’s quite related to what I have.

I tried to use this query, but when I run it, it errors with Column reference 'affiliate_code' is ambiguous:

INSERT INTO accounts (id, token, affiliate_code)
VALUES (value1, value2, value3)
ON CONFLICT (id) DO
UPDATE SET token = value2,
  affiliate_code = COALESCE(affiliate_code, value3);

(the real values are substituted, of course).

If I replace affiliate_code = COALESCE(affiliate_code, value3) with affiliate_code = value3, everything works, but not in the way I want it to work.

How can I make this work?

Here is how my table is defined:

CREATE TABLE accounts (
  id VARCHAR NOT NULL UNIQUE,
  token VARCHAR NOT NULL,
  affiliate_code VARCHAR
);

Published: 11 Apr 2015
Last Modified Date: 07 Apr 2023

Issue

When trying to refresh a data extract containing custom SQL, the following error might occur: 

ERROR: column reference «<field name>» is ambiguous; Error while executing the query 

Environment

  • Tableau Desktop
  • Tableau Data Extract
  • Custom SQL 

Resolution

Verify that the SQL Query completes successfully when run directly against the database. If the query does not complete successfully, work with your database administrator to address issues in the query. 

Cause

The error occurs within the data source and is not related to Tableau. 

Additional Information

More information on the «Column reference «<name>» is ambiguous error can be found below: 

  • Identifier Qualifiers at MySQL
  • 8 Tips Absolute Beginners can Use to Fix SQL Queries at Vertabelo Academy




Explanation: This error occurs when the referenced column cant be resolved unambiguously. This may occur when you have two tables that have columns with the same name.

How can you fix an ambiguous column reference error?

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.

What does it mean in SQL when something is ambiguous?

Ambiguous error means that you are calling a certain field in which exist in both Table and the SQL has no idea where to get it.

What is ambiguous error?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict.

What does column reference ambiguous mean?

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.

What is reference column in SQL?

Ambiguous error means that you are calling a certain field in which exist in both Table and the SQL has no idea where to get it.

What does ambiguous column name in SQL mean?

Explanation: This error occurs when the referenced column cant be resolved unambiguously. This may occur when you have two tables that have columns with the same name.

What does invalid column name mean?

Ambiguous error means that you are calling a certain field in which exist in both Table and the SQL has no idea where to get it.

What is meant by ambiguous in SQL?

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.

What does it mean when a field list is ambiguous?

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.

Where clause is ambiguous query?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict.

What is ambiguity error?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict.

What is ambiguous error in SQL?

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.

What is ambiguous error in C++?

Access to a base class member is ambiguous if you use a name or qualified name that does not refer to a unique function or object. The declaration of a member with an ambiguous name in a derived class is not an error. The ambiguity is only flagged as an error if you use the ambiguous member name.

What is ambiguity in Java?

The ambiguities are those issues that are not defined clearly in the Java language specification. The different results produced by different compilers on several example programs support our observations.

What is a column reference in SQL?

Explanation: This error occurs when the referenced column cant be resolved unambiguously. This may occur when you have two tables that have columns with the same name.

What is a reference table in SQL?

Table references are objects such as tables and views that you can include in an SQL statement. You can add table references at any time while you are working on the statement. You can create an SQL statement with multiple table references by using SELECT, FULLSELECT, and WITH statements.

What is Ref column?

A Ref column always stores the key column value of the referenced row. For example, if the key column value of a Customers row is Ann Adams then the Ref field in the related Orders row will contain the value Ann Adams . A tables key column value uniquely identifies each row in that table.

Why reference is used in SQL?

The references keyword is used to define which table and column is used in a foreign key relationship. This means that a record in the hobby table must have a person_id that exists in the person table or else at the time of insert you will receive an error that the key does not exist.

How does reference work in SQL?

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table

How do you name a column in SQL?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict.

Can we create two columns with same name in a relational table?

To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the tables column names: sp_columns @table_name News

Can a column name be null?

You cannot create two columns with exactly the same name.

Which is a valid column name?

Column names can contain any valid characters (for example, spaces). If column names contain any characters except letters, numbers, and underscores, the name must be delimited by enclosing it in back quotes (`).

How do you qualify a column name?

A qualifier for a column name can be a table name, a view name, an alias name, a synonym, or a correlation name. Whether a column name can be qualified depends, like its meaning, on its context. In some forms of the COMMENT and LABEL statements, a column name must be qualified

Answer by Arian Rosas

That means when you declare the function with RETURNS TABLE(jobnr character varying…, jobnr is an out parameter. Thus SELECT jobnr … is ambiguous.,Try declaring the function with aliases for the tables in your select:,with a parameter declaration. ,Try it with others names in the RETURNS clausule

Try declaring the function with aliases for the tables in your select:

CREATE OR REPLACE FUNCTION userdata.test3()
 RETURNS TABLE(jobnr character varying, ordernr character varying)
 LANGUAGE plpgsql
AS $function$
BEGIN
    RETURN QUERY
    SELECT  w.jobnr, w.ordernr
    FROM
        (SELECT wip.jobnr, wip.ordernr FROM userdata.WIP_Data as wip WHERE Year=2015 AND period=1) AS W

        LEFT OUTER JOIN
        (SELECT wip.jobnr, wip.ordernr FROM userdata.WIP_Data as wip WHERE Year=2015 AND period=2) AS P 
        ON W.Jobnr=P.Jobnr;
END; 
$function$

Answer by Emilio Briggs

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
,

Strong teams are more than just connected, they are communities

,Making statements based on opinion; back them up with references or personal experience.,Connect and share knowledge within a single location that is structured and easy to search.

The planner cannot understand which my_date you are mentioning there. Either the one in parameters or the one in the table1 (or table2). The correct syntax should be like the one below;

CREATE OR REPLACE FUNCTION test ()
RETURNS TABLE (
  my_date date, gates smallint, area_type character (1), 
  area_sizes float[], area_canvases float[]
)
AS $$
BEGIN
    RETURN query
    SELECT
        coalesce(s.my_date, r.my_date) AS my_date,
        coalesce(s.gates, r.gates) AS gates,
        coalesce(s.area_type, r.area_type) AS area_type,
        s.area_sizes,
        r.area_canvases
    FROM (
        SELECT
            t1.my_date,
            t1.gates,
            t1.area_type,
            t1.area_sizes
        FROM
            table1 t1
        WHERE
            t1.area_type = 'X') s
    FULL JOIN (
        SELECT
            t2.my_date, 
            t2.gates, 
            t2.area_type, 
            t2.area_canvases
        FROM
            table2 t2
        WHERE
            t2.area_type = 'Y') r ON r.my_date = s.my_date;
END
$$
LANGUAGE plpgsql;

Answer by Addison Glover

errorsfunctionsplpgsqlpostgresqlpostgresql-10,Postgresql – RETURN NEXT in Postgres Function,Postgresql – Postgres function return table with extra column,Postgresql – How to insert a record returned by a function into a table

This works:

CREATE OR REPLACE FUNCTION sql_fun()
RETURNS TABLE (id UUID) AS $$
  INSERT INTO foo DEFAULT VALUES
  RETURNING id
$$ LANGUAGE SQL;

SELECT *
FROM sql_fun();

This doesn’t:

CREATE OR REPLACE FUNCTION plpgsql_fun()
RETURNS TABLE (id UUID) AS $$
  BEGIN
    RETURN QUERY
    INSERT INTO foo DEFAULT VALUES
    RETURNING id;
  END
$$ LANGUAGE PLpgSQL;

SELECT *
FROM plpgsql_fun();

Answer by Idris Rhodes

Minimal SQL file that can be loaded into a clean database:,You can use the function name to disambiguate the field in postgres, e.g.:,Not related but if it can be asked here; I’m using uuid’s, and the following :, question (Please suggest another title, it could be wrong, i based it on the intuition i have about the issue)

create function sc.authenticate(_email text) returns sc.jwt_token as $$
    declare
      account sc.users;
    BEGIN
      IF EXISTS (select 1 from schema.table where sc.users.email = _email) THEN
        select a.* into account
        from sc.users as a
        where a.email = $1;
        return ('postgraphql_user_public', account.id)::sc.jwt_token;
      ELSE
        insert into sc.users(email)
        values ( _email)
        returning * into account;
        return ('postgraphql_user_public', account.id)::sc.jwt_token;
      END IF;
    END;
    $$ language plpgsql strict security definer;

Answer by Coen Lamb

I have a small project with Asp.Net Core 3.1 and using PostgreSQL database. Now I want to get all ticket of a member so I created a function database as below:,Asp.net core error: Unable to create an object of type ‘ApplicationDBContext’.,* Please polite comment and respect questions and answers of others.,In the PostgreSQL database, you have to define an alias for the table and using that alias to determine the columns of the table. You can change your database function as below:

 CREATE OR REPLACE FUNCTION public.func_ticket_getbymemberid (
  _memberid integer,
  _fromdate timestamp,
  _todate timestamp
)
RETURNS TABLE (
  id integer,
  memberid integer,
  createddate timestamp,
  score integer
) AS
$body$
BEGIN
    RETURN QUERY
    SELECT id, memberid, createddate, score
    FROM racinggameticket
    WHERE memberid = _memberid AND createddate between _fromdate AND _todate;
END
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100 ROWS 1000;

Answer by Nyla Blair

Example Postgres Log Output:,This error occurs when the referenced column can’t be resolved unambiguously. This
may occur when you have two tables that have columns with the same name.,Fix your query to include the specific table or view that the column belongs to.,In the example above, you would resolve this by adding an explicit table name
like this:

ERROR: column reference "z" is ambiguous at character 8
STATEMENT: SELECT z FROM x, y

Понравилась статья? Поделить с друзьями:
  • Column ambiguously defined oracle ошибка
  • Color laserjet pro mfp m176n ошибка сканера 22
  • Cocmainwin32 exe ошибка call of cthulhu как исправить
  • Color laser jet pro mfp m377dw ошибка 59 f0
  • Cobian backup теневое копирование ошибка