简体   繁体   中英

Query to bring top 3 users from top 3 cities in SQL

I have a location (city) table and a user table. I need to retrieve the 3 top users from 3 top cities (where a city is considered as a top 3 depending on how many users there are in it), with the city information. Example:

Miami (q = 95000)

  1. Andrea
  2. Debra Morgan
  3. Gabriela

New York (q = 74000)

  1. Sandy
  2. Carsie
  3. Megan

San Diego (q = 26500)

  1. Ursula
  2. Ramona
  3. Romina

This is my current query:

SELECT l.city, l.q, u.name 
FROM location AS l JOIN user AS u 
ON l.id_location = u.id_location 
ORDER BY q DESC 
LIMIT 3

The obvious problem is that it is only bringing me the top 3 users from the top 1 city. Any ideas?

These are the tables:

location

  • id_location
  • name
  • q (amount of users)

user

  • id_user
  • name
  • picture

You could use GROUP_CONCAT function to concatenate all users, and SUBSTRING_INDEX to return only the first three users:

SELECT
  l.city, l.q
  SUBSTRING_INDEX(
    GROUP_CONCAT(u.name ORDER BY field_to_order DESC), ',', 3
  ) AS top_3_users
FROM
  location AS l JOIN user AS u 
  ON l.id_location = u.id_location
GROUP BY
  l.city, l.q
ORDER BY
  l.q DESC
LIMIT 3

result will be something like this:

Miami     95000    Andrea, Debra Morgan, Gabriela
New York  74000    Sandy, Carsie, Megan
San Diego 26500    Ursula, Ramona, Romina

Edit if you also need the picture of the user, and the picture is a VARCHAR, then you can use GROUP_CONCAT also on that field:

SELECT
  l.city, l.q
  SUBSTRING_INDEX(
    GROUP_CONCAT(u.name ORDER BY field_to_order DESC), ',', 3
  ) AS top_3_users,
  SUBSTRING_INDEX(
    GROUP_CONCAT(u.picture ORDER BY field_to_order DESC), ',', 3
  ) AS top_3_pictures
FROM
  location AS l JOIN user AS u 
  ON l.id_location = u.id_location
GROUP BY
  l.city, l.q
ORDER BY
  l.q DESC
LIMIT 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM