简体   繁体   中英

Return rows with the highest value on one column corresponding to a given value in another

There's a MySQL table named raw_contacts with the following structure:

ID (primary auto-increment, int)
PHONE (composite unique with NAME, varchar)
NAME (composite unique with PHONE, varchar)
FREQUENCY (int)
Composite unique key is named PHONENUM

I am trying to write a query to return the row with the highest corresponding value in the FREQUENCY column for any given value for PHONE. I did find a related post but the accepted answer doesn't work for my case since I have a composite key of two columns to run the check against.

Just to illustrate, consider the following sample:

1 1234 John 6
2 1234 Dave 2
3 2199 Bill 9
4 1878 Dani 3
5 1234 Cory 7
6 1234 Gore 5
7 3319 Cory 1

Run against 1234 on the above sample, the query should return the 5th row since Cory has the highest count in the FREQUENCY column for that number.

Here's what I've come up with and it works great:

select RC.ID, RC.PHONE, RC.FREQUENCY, RC.NAME
from `raw_contacts` RC
inner join(
    select PHONE, max(FREQUENCY) FREQUENCY
    from `raw_contacts`
    where PHONE="11111"
    group by PHONE
) RC2 on RC.PHONE = RC2.PHONE and RC.FREQUENCY = RC2.FREQUENCY
limit 1

Is there any more resource-friendly query for this task since it needs to run at a very high frequency on a table with millions of records? I'm looking to optimize it to the bone!

PS In case of more than one rows qualifying, I need only one of them, which one doesn't matter.

join is a costly operation in DB and I think you must avoid using it as much as possible!!! I suggest to use the following query and compare its result with your one.

select * from `raw_contacts` RC1 where PHONE="11111" 
and FREQUENCY>=all (select FREQUENCY from `raw_contacts` RC2 where RC2.PHONE=RC1.PHONE) LIMIT 1

also you can consider different types of indexing ( a good toturial is here ) on your table to speedup special and more frequent queries

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