Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select a value from a table using table column key

I have the following Postures table:

CREATE TABLE users
(
    id bigint NOT NULL,
    created_by character varying(255) COLLATE pg_catalog."default",
    creation_date timestamp(6) without time zone,
    default_travel_method_id character varying(255) COLLATE pg_catalog."default",
    default_shipping_address_id character varying(255) COLLATE pg_catalog."default",
    CONSTRAINT users_pkey PRIMARY KEY (id)
)

When I use this select to select also a column from another table I use this in Oracle:

    SELECT
    created_by,
    (select reference from methods where id = default_travel_method_id) as default_travel_id,
    (select reference from addresses where id = default_shipping_address_id) as defaultShippingAddressId,
    from users;

But in Postures I get this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ERROR:  operator does not exist: bigint = character varying
LINE 8: ...reference from methods where id = default_...
                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts. 

Do you know in Postgres what is the proper way to use a column expression to select a value from another table?

>Solution :

Typically you wouldn’t use character varying for a foreign key. Define the table using traditional integer id fields:

CREATE TABLE users
(
    id bigint NOT NULL,
    created_by character varying(255) COLLATE pg_catalog."default",
    creation_date timestamp(6) without time zone,
    default_travel_method_id int references methods(id),
    default_shipping_address_id int references addresses(id),
    CONSTRAINT users_pkey PRIMARY KEY (id)
)

Then select with a JOIN, assuming your related tables have id and reference columns

SELECT
  created_by,
  methods.reference AS "defaultTravel",
  addresses.reference AS "defaultShippingAddress"
FROM
  users
JOIN methods ON
  methods.id = default_travel_method_id
JOIN addresses ON
  addresses.id = default_shipping_address_id
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading