How do I INNER JOIN in this case?

1

I am a beginner in PostgreSQL and I need to make a INNER JOIN to relate data from two tables. It took me a long time to figure this out from FOREIGN KEY , but I made the right reference in the database. Now, I have a C # application and I'm not sure how I should write the table read command and data relation.

The current command structure follows:

SELECT * FROM users_data WHERE user_id = {0}

What leaves me in doubt is where to put INNER JOIN , AS , and ON . The users_data table has a user_type column and this value must be toggled with the users_type table.

    
asked by anonymous 10.06.2017 / 01:04

2 answers

3

You should do this:

SELECT * 
FROM users_data a
INNER JOIN users_type b ON b.id = a.user_type_id 
WHERE user_id = {0}

This takes into account that your table "users_data" has the field "user_type_id" which is your foreign key.

For you to understand better:

"INNER JOIN" is using you to join two tables. You could have multiple inner join in a query, in which case you are merging multiple tables into one query.

"ON" is used next to the INNER JOIN clause to indicate the fields that relate.

"AS" is used to rename the fields of your query. In case here it was not used.

Abs!

    
10.06.2017 / 01:43
3

Do this:

SELECT * 
FROM users_data 
     INNER JOIN user_type AS NomeAlias ON users_data.valor = NomeAlias.valor 
WHERE user_id = {0}

Where valor would be the relationship between tables, such as an ID or something like that.

Another example:

SELECT p.descricao, p.preco_custo, preco_venda, p.qtd_estoque, 
       p.qtd_estoque_minimo, marca.nome 
FROM produto as p
     INNER JOIN marca AS marca ON marca.id = p.id_marca
ORDER BY marca.nome

But you need to see what kind of relationship you want to make.

There are differences between Join , Left Join , Right Join and Inner Join .

    
10.06.2017 / 01:43