SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2008
    Posts
    118
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Retrieve two values from the same column as two columns

    This is probably something simple, but I just can't think of how to do it. I have a table called categories with two columns, Key and Category. I want to select the keys from the table for one value as a Main category, and one as a Sub category. So, I have a query as follows:
    Code:
    SELECT MainCatKey,SubCatKey FROM
    (SELECT `Key` AS MainCatKey FROM categories WHERE Category = 'some category name') AS MainCat,
    (SELECT `Key` AS SubCatKey FROM categories WHERE Category = 'some other category name') AS SubCat
    The problem is that if one of the categories doesn't exist, then the query returns no rows. What I really want is that if one of the subqueries returns no rows, I still get a result set, but with NULL for the empty result. Using the above example, if 'some category name' didn't exist, but 'some other category name' did exist, and had a Key of 123, then I'd want to get a result set of
    Code:
    MainCat | SubCat
    NULL    | 123
    rather than just an empty result.

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,334
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    Code:
    SELECT 'maincat' as keytype
         , `Key` 
      FROM categories 
     WHERE Category = 'some category name'
    UNION ALL
    SELECT 'subcat' as keytype
         , `Key` 
      FROM categories 
     WHERE Category = 'some other category name'
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Zealot
    Join Date
    Dec 2008
    Posts
    118
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •