how to make a Join Inner picking up the description

Asked

Viewed 41 times

1

my tables:

agencias (id, nome_agencia, ads -> FK pra tabela de baixo)
ads (id, nome, agencia -> essa é FK pra tabela anterior)

the problem is this: each agency will have an ads in the ads has a main agency

want to make a select displaying agencia_id, agencia_name, ads_id, ads_name_agencia

I tried this, but I don’t know how to "fit" the agency name

SELECT agencias.id as id_agencia, agencias.nome as agencia_nome, ads.id as id_ads, ads.agencia as ads_agencia_id
FROM agencias
INNER JOIN ads
ON agencias.id=ads.agencia

1 answer

2

You just need to give a "nickname" to your tables

SELECT 
    ag.id as id_agencia, 
    ag.nome as agencia_nome, 
    ad.id as id_ads, 
    ad.agencia as ads_agencia_id
FROM 
    agencias ag
INNER JOIN ads ad ON ad.id = ag.ads -- ag.ads = FK ads -> agencia
  • running this query resulted in the following: id_agencia, agencia_nome, id_ads, ads_agencia_id ...... I need tb to return the agency name q is referenced in ads_agencia_id

  • Just refer to it in select. ad.nome, where ad is the nickname that was set for the table and then the name of the field. You will do so to add all the fields you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.