M
M
Manu_habr2021-03-13 14:31:15
SQL
Manu_habr, 2021-03-13 14:31:15

How to form a query so that the limit is for a certain number of unique fields?

There is a request like this:

SELECT 
       contacts.id as id, 
       contacts.name as name, 
       phone.phone as phone, 
       email.email as email 
FROM contacts 
LEFT JOIN phone 
ON 
contacts.phone = phone.phone_id 
LEFT JOIN email 
ON 
contacts.email = email.email_id
LIMIT 6


Which returns:
604ca204d1c3f508190072.jpeg

How to make LIMIT not by the number of records, but by the number of unique fields in the name column?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-03-13
@Manu_habr

The first thing that comes to mind is GROUP BY , but with it you will have to somehow aggregate the rest of the fields.
Another option is to make a request for a request with a limit, something like:

SELECT 
       c.id AS id, 
       c.name AS name, 
       phone.phone AS phone, 
       email.email AS email 
FROM (SELECT id, name, phone, email FROM contacts LIMIT 6) AS c 
LEFT JOIN phone 
       ON c.phone = phone.phone_id 
LEFT JOIN email 
       ON c.email = email.email_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question