views:

307

answers:

2

I want to write a query that will match up a string from one table with the closest alphabetical match of a string fragment within another table.

Given: There are 2 tables, table 1 has a record with string "gumby". Table 2 has letters that start words: "g", "ga", "gam", "go", "ha", "hi".

Problem: Because I don't have a "gu" entry or anything more specific (like "gum"), I want "gumby" to match up with "go", because alphabetically "gumby" is less than "h" and more than "go".

Mechanisms I have tried: 1. A statement with "LIKE g%" will return all fragments starting with "g", I only want one result.
2. A statement with "LIKE "g%" and a GROUP BY. That only returns "g".
3. Adding MAX() to that GROUP BY statement will give me "go", but that's not correct if my word were "galaga" -- the correct spot for that would be "ga".

I would really like to accomplish this alphabetizing words solely in SQL.

+5  A: 

SQL compares with the dictionary in mind. You can use this to your advantage, like so:

select
    max(word)
from
    table2 t2
where
    word < @word

To get the list of all words from table1 and the corresponding word from table2, you'd do this:

select
    t1.word,
    (select max(word) as word from table2 where word <= t1.word) as Dictionary
from
    table1 t1
Eric
I didn't think of this because I'm not a cool guy like Eric. +1 for showing me that I'm a moron.
Welbog
@Welbog: I would have linked to your answer, but you baleted it.
Eric
@Eric: What happens in meta stays in meta.
Welbog
A: 

What about something like

select word from Table_1 where work like 'g%' order by word asc LIMIT 0,1

I'm not sure if that's the exact synatx for Limit, it's been a while since I used mysql

cptScarlet
This...wouldn't work at all, I'm afraid. It would return 'go' for all 'g' words. Which is entirely the wrong result.
Eric
Since i'm ordering in ascending order the front of the alphabet would be returned first. So "ga" would be returned not "go". At least this is how it's working in sql server
cptScarlet
@Scarlet: So 'ga' would be returned for 'gumby', which is invalidating the OP's requested result set.
Eric
Ahh yes, now I see. Thanks, too bad you can't get credit for two answers on one post
cptScarlet