Is it possible to do this in MySQL?

Discussion in 'MySQL' started by Sleepless, Feb 29, 2008.

  1. #1
    I wonder if this can be done in MySQL.

    There are two tables:
    T1 has two columns - people and countries (T1.name, T1.country).
    T2 has two columns - countries and URLs (T2.country, T2.url).

    There is one special record in Table 2 - the "default URL", where the country is NULL.

    Given a person's name, I want to find the URL for that person's country. However, if the country does not exist in table 2, I want to return the default URL.

    So basically the query is
    SELECT T2.url FROM T1, T2 WHERE T1.country = T2.country and T1.name = 'John';
    Code (markup):
    but it doesn't take into account the case where the country does not exist in table.

    Any ideas?
     
    Sleepless, Feb 29, 2008 IP
  2. alemcherry

    alemcherry Guest

    Best Answers:
    0
    #2
    You can add a null condition , or have a query with join.
     
    alemcherry, Feb 29, 2008 IP
  3. Sleepless

    Sleepless Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks - but if I add a NULL condition, it will return both records in case the country does exist in T2:

     
    Sleepless, Feb 29, 2008 IP
  4. pkerr1975

    pkerr1975 Peon

    Messages:
    13
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You can probably do a Left Join from table t1 to table t2

    Then to cater for the possibility of a NULL result for country use the IFNULL() control function to replace it with the value you want.

    You will likely need to embed a select statement within the function to retrieve the default.

    Hope this helps
     
    pkerr1975, Feb 29, 2008 IP
  5. theweekendchef

    theweekendchef Peon

    Messages:
    69
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Use case statement:

    SELECT T2.url FROM T1, T2 WHERE
    T1.name = 'John' AND
    CASE
    WHEN T1.country = T2.country THEN T2.url
    ELSE Default
    END CASE
    ;
     
    theweekendchef, Mar 3, 2008 IP
  6. Sleepless

    Sleepless Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Thank you!
     
    Sleepless, Mar 3, 2008 IP