MYSQL relationship between tables

1

I'm not very good with database relationships and I'm starting my studies.

I would like to know why developers shorten when calling tables or if this is mandatory?

SELECT p.*, c.'nome' AS categoria, u.'nome' AS usuario FROM 'produtos' AS p
INNER JOIN 'categorias' AS c ON p.'categoria_id' = c.'id'
INNER JOIN 'usuarios' AS u ON p.'usuario_id' = u.'id'
WHERE (p.'ativo' = 1) ORDER BY p.'nome' ASC

This is very confusing, I know that he is joining 2 tables in a query but I do not understand this:

 p.* , p.´nome´,  c.'nome', u.'nome'
    
asked by anonymous 29.05.2017 / 20:56

3 answers

3

The item p. * means that it is to display all fields in the products table. Right after FROM, you have written products as p, that is a short name so you do not have to write products. . As the nickname p was created, you simply reference it using p. .

The item p.name, references the product table and column name, says that it is to sort the result by the column name of the product table. It is just a short name, could be written product.name, but as I mentioned above, it has been given a nickname "p" and reference can be made as p.name.

I'm happy to help.

    
29.05.2017 / 21:00
4

Generally, you create this "alias" for the tables and columns to make it easier to reference them again in the query.

For example, instead of writing category every time, just type c. This is not mandatory, but when there are tables you want to relate that have columns with the same name, when you are going to use these columns you need to tell which table and there it makes sense to use the alias.

    
29.05.2017 / 21:01
2

Generally it is used to name the tables to facilitate the writing of the Script that by syntax asks the use of "Table name" and "Field name" (ex: category.name) in cases where the field name exists in more than one table.

SELECT p.*, c.nome AS categoria, u.nome AS usuario  
FROM produtos p  
INNER JOIN categorias c ON p.categoria_id = c.id  
INNER JOIN usuarios u ON p.usuario_id = u.id  
WHERE (p.ativo = 1)  
ORDER BY p.nome  
ASC
    
29.05.2017 / 21:02