I
I
Ivan Melnikov2020-10-27 20:59:48
SQL
Ivan Melnikov, 2020-10-27 20:59:48

How to LEFT JOIN th add only one term, and not any, but the largest in this field?

Let there be two tables:
Clients
-------
Ivan
Anna
Rita

Telephones
-------------
Ivan | 854
Ivan | 921
Rita | 321
Anna | 111

Only one number for each client should be added to the first tablet, and the largest among the numbers of this client.
That is, you need to get:
Ivan | 921
Anna | 111
Rita | 321.
Tell me, please, how to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitsliputsli, 2020-10-28
@immelnikoff

select
        u.*,
        ph.phone_max
    from users u
    left join (
        select 
                user_id, max(phone) phone_max
            from phones 
            group by user_id
    ) ph on u.user_id=ph.user_id

A
alexalexes, 2020-10-27
@alexalexes

If you only want the phone number from the join table and nothing else, a subquery as a property using max.

select C.Name,
(select max(T.Phone) from Telephone T where T.Name = C.Name) Max_Phone
from Clients C

PS: If this is a practical task, and not a theoretical warm-up, then it should be confusing to use the customer name as the primary key in the customer table and as a foreign key in the phone table. In practice, identifiers are usually used to link tables.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question