Frage

This my table

prefix | rate   | provider
------------------------
21366  | 0.1951 | ES
213    | 0.0554 | ES
213    | 0.0567 | 3LV
2136   | 0.189  | 3LV
213    | 0.0481 | vbP
21366  | 0.1894 | vbP
44     | 0.05   | ES
44     | 0.004  | vbP

How can | select the lowest rate for prefix X with the max length of a prefix between all providers.

for example for this prefix 21366 The result set should look like that

2136   | 0.189  | 3LV - The Winner
21366  | 0.1894 | vbP
21366  | 0.1951 | ES

If the provider has the exact prefix 21366 then it will be the row that will be compared with the other providers' rates. If the provider doesn't have the exact prefix, then we try to find the longest common string between wanted prefix and the provider's prefixes.

I use this condition to match prefixes WHERE 21366 LIKE CONCAT( prefix , '%' )

So first, find the prefix each provider. Then select the lowest rate between the providers

War es hilfreich?

Lösung

This query should return the rows that you need:

SELECT tablename.*
FROM
  tablename INNER JOIN (
    SELECT
      provider, MAX(LENGTH(prefix)) as max_length
    FROM
      tablename
    WHERE
      '21366' LIKE CONCAT(prefix, '%')
    GROUP BY
      provider) m
  ON tablename.provider = m.provider
     AND LENGTH(prefix)=m.max_length

Please see fiddle here. You might also want to add this to your query:

ORDER BY
  rate
LIMIT 1

if you just need the lowest rate.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top