SQL Join multiple tables only the 1st result

Asked

Viewed 50 times

0

I have 3 tables:

**clientes**
cli_cliente   nome
50            A
52            B

**telefones_cliente**
cli_cliente  tel_telefone
50           387
50           386
50           385
52           400

**telefones**
tel_telefone    tel_contato
385             RODOLFO - COMPRAS
386             SONIA CONTAS A PAGAR RAMAL 201
387             VANESSA CONTABILIDADE RAMAL 202
388             (null)
389             (null)

I need as a result customers and only the first phone table phones_clients to use this information to pick up phones.tel_phone and phones.tel_contact. I’ve made several attempts to filter, but I always get back all the client’s phones, I need help. This is my last SQL that also does not work.

SELECT
c.cli_cliente
,cli_razao_social,
tc.tel_telefone
--  ,telefones.tel_contato
  FROM
    clientes c
  JOIN telefones_cliente tc ON c.cli_cliente = (SELECT tc.cli_cliente FROM telefones_cliente, clientes c2, telefones t WHERE c2.cli_cliente=tc.cli_cliente AND tc.tel_telefone=t.tel_telefone LIMIT 1)

My result is this:

cli_cliente cli_razao_social                        tel_telefone
50          EXACTA ENGENHARIA E ADMINISTRAÇAO LTDA  385
50          EXACTA ENGENHARIA E ADMINISTRAÇAO LTDA  386
50          EXACTA ENGENHARIA E ADMINISTRAÇAO LTDA  387

When I need this:

cli_cliente cli_razao_social                        tel_telefone
49          WOOD FORM LTDA                          384
50          EXACTA ENGENHARIA E ADMINISTRAÇAO LTDA  387

1 answer

1

I suggest you use some group function such as MAX or MIN to return only one phone.

Something more or less like this:

SELECT 
   c.cli_cliente,
   c.nome,
   tc.tel_telefone 
FROM 
   clientes c 
   JOIN (
      SELECT 
         tc.cli_cliente,
         MAX(tc.tel_telefone) tel_telefone
      FROM 
         telefones_cliente tc
      GROUP BY 
         tc.cli_cliente
   ) tc ON tc.cli_cliente = c.cli_cliente

Browser other questions tagged

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